Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sure that a method is used after an object is created in golang?

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.

like image 894
scott Avatar asked Dec 24 '22 06:12

scott


2 Answers

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.

like image 142
icza Avatar answered May 10 '23 14:05

icza


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?

like image 42
Andreas Schyman Avatar answered May 10 '23 15:05

Andreas Schyman