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

狂风中的少年 提交于 2019-12-19 03:41:19

问题


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.


回答1:


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.

A good design is to make your type unexported, but provide an exported constructor function like NewMyType() in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course. 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.




回答2:


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?



来源:https://stackoverflow.com/questions/36826232/how-to-make-sure-that-a-method-is-used-after-an-object-is-created-in-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!