There is no way to force the call of a Close()
method. The best you can do is document it clearly that if the value of your type is not needed anymore, its Close()
method must be called.
In the extreme situation when a program is terminated forcibly, you can't have any guarantees that any code will run.
Note that there is a runtime.SetFinalizer()
function which allows you register a function which will be called when the garbage collector finds a value / block unreachable. But know that there is no guarantee that your registered function will be run before the program exits. Quoting from its doc:
There is no guarantee that finalizers will run before a program exits, so typically they are useful only for releasing non-memory resources associated with an object during a long-running program.
You may choose to make your type unexported, and provide an exported constructor function like NewMyType()
in which you can properly initialize your struct / type. You can't force others to call its Close()
method when they are done with your value, but at least you can stop worrying about improper initialization.