djhaskin987
djhaskin987

Reputation: 10057

const methods in golang?

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?

Upvotes: 8

Views: 7330

Answers (2)

ijt
ijt

Reputation: 3825

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}

Upvotes: 3

Volker
Volker

Reputation: 42433

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.

Upvotes: 15

Related Questions