const methods in golang?

huangapple go评论86阅读模式
英文:

const methods in golang?

问题

在Go语言中,通常你想要声明一个与指针类型相关联的方法,因为你不想复制一个庞大的结构体:

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

在C++中,当我想要创建这样一个方法,但又要保证它不会改变底层结构体时,我会声明它为const

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

在Go语言中是否有相应的方法?如果没有,是否有一种惯用的方式来创建一个与指针类型相关联的方法,而又不会改变底层结构体?

英文:

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?

答案1

得分: 15

不,没有。

此外,你的论点“因为你不想复制一个庞大的结构体”往往是错误的。很难想出真正那么大的结构体,在方法调用期间复制会成为应用程序的瓶颈(请记住,切片和映射是小的)。

如果你不想改变你的结构体(当你考虑到映射或指针字段时,这是一个复杂的概念):就不要这样做。或者进行复制。如果你担心性能问题:进行测量。

英文:

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.

答案2

得分: 2

如果你想确保不改变方法的目标,你必须声明它不是一个指针。

package main

import (
	"fmt"
)

type Walrus struct {
	Kukukachoo int
}

func (w Walrus) foofookachu() {
	w.Kukukachoo++
}

func main() {
	w := Walrus{3}
	fmt.Println(w)
	w.foofookachu()
	fmt.Println(w)
}

===

{3}
{3}

英文:

If you want to guarantee not to change the target of the method, you have to declare it not to be a pointer.

    package main

    import (
            "fmt"
    )

    type Walrus struct {
            Kukukachoo int
    }

    func (w Walrus) foofookachu() {
            w.Kukukachoo++
    }

    func main() {
            w := Walrus { 3 }
            fmt.Println(w)
            w.foofookachu()
            fmt.Println(w)
    }

    ===

    {3}
    {3}

huangapple
  • 本文由 发表于 2015年5月13日 00:07:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/30196175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定