This is a creation in Article, where the information may have evolved or changed.
Golang supports structs as well as pointers to structs. A common puzzle is that since the struct pointer exists, why not simply a struct pointer? Two reasons:
struct cannot be empty, and struct pointer can be nil
[]my_struct's memory is contiguous, while []*my_struct only the pointer is contiguous, while the actual content needs to follow the pointer to read
At the same time, structs should also help escape analysis so that objects can be allocated on the stack without having to scramble the memory on the allocated heap for multithreading. But it's just a conjecture.
A more interesting question is, when should a method be bound to a struct rather than a struct pointer? Consider the following test procedure
type MyStruct struct { field int}
local_variable := MyStruct{1}fmt.Println(unsafe.Pointer(&local_variable))local_variable.modify_struct_value()fmt.Println(local_variable) // {1}copied := local_variable.copy_my_self()fmt.Println(unsafe.Pointer(&copied))
func (self MyStruct) modify_struct_value() { fmt.Println(unsafe.Pointer(&self)) self.field = 2}func (self MyStruct) copy_my_self() MyStruct { fmt.Println(unsafe.Pointer(&self)) return self}
The output that is executed is
0xc82000a2c80xc82000a2e0{1}0xc82002a0280xc82000a2f0
This proves a few things.
The struct was copied a copy of the method before it was executed.
Modifications to this copy will not affect the original struct (nonsense)
If the copy is returned to the caller, the caller will copy it again (without return value optimization) while saving the local variable.
According to this behavior, unless we want a method that is similar to the const behavior of C + + (at the expense of a memory copy), there is basically no reason to bind the behavior on a struct rather than on a struct pointer in other scenarios.
Conclusion:
struct because it can control memory layout, it has its existence meaning. Performance-insensitive scenarios, always using struct pointers without feeling guilty.
Always bind a method to a struct pointer instead of binding on a struct to avoid unnecessary memory copies