I want to run a method when an object destroyed,how to do ?

xuanbao · · 559 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Is there a method like the destruct method in c++?</p> <hr/>**评论:**<br/><br/>dgryski: <pre><p><a href="https://golang.org/pkg/runtime/#SetFinalizer" rel="nofollow">https://golang.org/pkg/runtime/#SetFinalizer</a> but note that you have no guarantee when it will run, or even if it will run at all. Best to add an explicit Close to your type.</p></pre>mattn: <pre><p>C++ ensure calling the destructor when the instance of object goes out of the scope. But Go or some programming language that uses GC doesn&#39;t ensure the calling. Because GC will be run in the time when Go&#39;s scheduler want to do. So SetFinalizer may not match your expected. I suggest to use contract-programming that use interface WriteCloser that dgryski says.</p></pre>wangshaonan: <pre><p>I want to write a class for db connection ,just like a mysql connection ,user call connect method at start .But if user don&#39;t call close method explicitly before GC ,I want the connection will be close too. </p></pre>natefinch: <pre><p>I think you need to post what kind of problem you&#39;re trying to solve, because it&#39;s hard to help when you ask about a solution, not the problem. </p></pre>wangshaonan: <pre><p>I want to write a class for db connection ,just like a mysql connection ,user call connect method at start .But if user don&#39;t call close method explicitly before GC ,I want the connection will be close too. </p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

559 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传