7

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?

djhaskin987
  • 9,741
  • 4
  • 50
  • 86

2 Answers2

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.

Volker
  • 40,468
  • 7
  • 81
  • 87
2

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}
ijt
  • 3,505
  • 1
  • 29
  • 40
  • 1
    This is not what OP was asking, because this is not the "equivalent" of C const qualifier. The exact answer to OP's question is simply "no". – Zhe May 06 '23 at 11:23
  • @Zhe, that may be technically accurate, but I'm trying to be helpful more than pedantic. – ijt May 08 '23 at 23:43