如何确保在golang中创建对象后使用方法? [英] How to make sure that a method is used after an object is created in golang?

查看:202
本文介绍了如何确保在golang中创建对象后使用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 struct ,并且有一个我写的 new 方法,返回它的指针。

现在我还有另一个方法,例如 Close ,但是到目前为止,它是在创建对象后不一定要调用此方法。我想确保在创建对象时必须调用此方法。我如何在Golang中做到这一点?如果这是可能的,我不知道这是什么。请帮忙。谢谢。

解决方案

无法强制调用 Close()方法。你可以做的最好的事情就是清楚地记录下来,如果你的类型的值不再需要,必须调用它的 Close()方法。



在程序强行终止的极端情况下,您不能保证任何代码都能运行。



请注意,是 runtime.SetFinalizer() 函数,它允许你注册一个函数,当垃圾收集器发现一个值/块不可访问时将被调用。但是要知道,在程序退出之前不能保证你的注册函数会被运行。从它的文档引用:


无法保证在程序退出之前终结器会运行,因此通常它们仅用于释放非终结符在一个长期运行的程序中与一个对象关联的内存资源。

一个好的设计是让你的类型不导出,但是提供一个导出像 NewMyType()这样的构造函数,可以在其中正确地初始化你的结构/类型。同时返回一个接口类型而不是一个具体类型,接口应该包含其他人想要处理的值。当然你的具体类型必须实现那个接口。当你的值完成后,你不能强迫别人调用它的 Close()方法,但至少你可以停止担心不正确的初始化。


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.

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.

这篇关于如何确保在golang中创建对象后使用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆