doujiao9574 2016-04-24 17:02
浏览 94
已采纳

在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.

  • 写回答

2条回答 默认 最新

  • dqwh1219 2016-04-24 17:12
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码