英文:
How to make sure that a method is used after an object is created in golang?
问题
我有一个struct
,我编写了一个new
方法,用于生成对象并返回其指针。
现在我还有另一个方法,例如Close
,但目前并不需要在创建对象后调用此方法。我想确保如果创建了对象,就必须调用此方法。在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.
答案1
得分: 10
没有办法强制调用Close()
方法。你能做的最好的办法是清楚地记录下来,如果你的类型的值不再需要,必须调用它的Close()
方法。
在程序被强制终止的极端情况下,你不能保证任何代码会运行。
请注意,有一个runtime.SetFinalizer()
函数,允许你注册一个函数,当垃圾收集器发现一个值/块不可达时,该函数将被调用。但要知道,不能保证你注册的函数会在程序退出之前运行。引用它的文档:
> 不能保证在程序退出之前会运行终结器,因此它们通常只在长时间运行的程序中用于释放与对象关联的非内存资源。
你可以选择将你的类型设为非导出的,并提供一个导出的构造函数,比如NewMyType()
,在其中你可以正确地初始化你的结构/类型。当其他人使用完你的值后,你无法强制他们调用Close()
方法,但至少你不用再担心不正确的初始化了。
英文:
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.
答案2
得分: 2
简而言之,在Go语言中是不可能的。
你要找的术语是析构函数,而Go语言没有实现析构函数。要了解更多信息,请阅读这里的优秀答案:Go destructors?
英文:
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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论