dongshendie8849 2015-05-12 08:07
浏览 202
已采纳

Golang中的const方法?

In golang, often you want to declare a pointer-type associated method, because you don't want to copy a huge struct around:

func (a *HugeStructType) AMethod() {
    ....
}

In C++, when I wanted to make such a method, but guarantee that it didn't mutate the underlying struct, I declared it const:

class HugeStructType {
    public:
        void AMethod() const
        ...
}

Is there an equivalent in golang? If not, is there an idiomatic way to create a pointer-type-associated method which is known not to change the underlying structure?

  • 写回答

2条回答 默认 最新

  • douque2016 2015-05-12 08:26
    关注

    No there is not.

    Additional your argument that "because you don't want to copy a huge struct around" is wrong very often. It is hard to come up with struct which are really that large, that copies during method invocation is the application bottleneck (remember that slices and maps are small).

    If you do not want to mutate your structure (a complicated notion when you think about e.g. maps or pointer fields): Just don't do it. Or make a copy. If you then worry about performance: Measure.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部