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?
In Go, const is a keyword introducing a name for a scalar value such as 2 or 3.14159 or "scrumptious" . Such values, named or otherwise, are called constants in Go. Constants can also be created by expressions built from constants, such as 2+3 or 2+3i or math.Pi/2 or ("go"+"pher").
A method consists of the func keyword, the receiver argument, and the function body. Here is the syntax of a Go method. So, when we want to call the function we simply do receiver.funcName (arg).
It is really useful to do so since structs are the closest thing to a class in Go. They allow data encapsulation and with the methods described they will behave as a class does in an OOP language. Here is an example showing methods on a struct. fmt.Println (h.name, "is", h.age, "years old.")
A var declaration can have more than one variable in it, and each can have a separate value. But only one type can be used. All variables use the specified type. Quote: If a type is present, each variable is given that type (Go Specification). With const and iota, Go provides compile-time code generation features.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With