You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+17-1Lines changed: 17 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -8,7 +8,12 @@ It provides two methods:
8
8
-`object.Defer` to defer closing the resources created by the current object (for example `foo.Defer(foo.db.Close)`).
9
9
-`object.Close`, once called, executes all of the deferred operations and returns errors if necessary.
10
10
11
-
Additionally, `ex.Terminate` helps you to find leaks by reporting errors if an object gets garbage-collected without having been closed.
11
+
Additionally, `ex.Terminate` helps you find leaks by reporting errors if an object gets garbage-collected without having been closed.
12
+
13
+
`ex.Terminator` has several benefits over maintaining your own `Close` methods:
14
+
- Similarly to the `defer` keyword, it is easier to keep track of what is being closed or not, because both the open and close operations always goes together. Meanwhile, it is very easy to forget about it when writing or maintaining a `Close` method.
15
+
- Errors in manually maintained `Close` methods are often ignored, and handling it explicitly makes the readability worse. `ex.Terminator` takes care of that for you, and includes helpful error messages.
16
+
-`ex.Terminator` takes care of closing the resources in the right order, which is easy to get wrong when manually done.
12
17
13
18
## Example
14
19
@@ -96,6 +101,17 @@ func main() {
96
101
}
97
102
```
98
103
104
+
## Is this based on `runtime.SetFinalizer`?
105
+
106
+
No. Resources are closed synchronously, meaning that the `Close` methods still must be called, either via `defer`, `.Defer` or manually.
107
+
108
+
However, `ex.Terminator` uses `runtime.SetFinalizer` to help the developers find mistakes: an error message is printed in the console whenever a non-Closed object gets garbage-collected.
109
+
But this only used for this purpose. Closing the objects is never done in `SetFinalizer`.
110
+
111
+
## Can I use it outside the constructor?
112
+
113
+
Yes! Although I only provided examples using the constructor (because it is the most common use case), you can use `.Defer` in any method and any time of the life-cycle of your objects.
114
+
99
115
## In which order are resources closed?
100
116
101
117
`ex.Terminator` follows the same convention than the `defer` keyword: the last deferred operation is executed first:
0 commit comments