I have a struct
, and I have a new
method that I have written, that generates the object and return its pointer.
Now I also have another method for example, Close
, but as of now, it is not mandatory to call this method once the object is created. I want to make sure that this method has to be called if the object is created. How do I do that in Golang? If this is possible, I don't know what is this termed as either. Please help. Thank you.
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.
In short, it is not possible in go.
The term you are looking for is destructors, which Go does not implement. For more information, read through the excellent answer here: Go destructors?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With