In the process of writing code, often will be involved in the method of receiver type selection problem, often tangled in the use of T or *t, remember the following principles to solve the problem:
- To modify the instance state, use *t.
- It is recommended to use T for small objects or fixed values without modifying the state.
- Large objects are recommended with *t to reduce replication costs.
- Reference types, strings, dictionaries, functions, and other pointers wrap objects directly with T.
- If synchronization fields such as mutexes are included, use *T to avoid invalid lock operations due to assignment.
- Other uncertain situations are *t.
Methods can be invoked using instance values or pointers, and the compiler will automatically convert between the underlying type and pointer type based on the method receiver type.
type N intfunc (n N)Value(){ n++ fmt.Printf("%p, %v\n",&n,n)}func (n *N)Pointer(){ *n++ fmt.Printf("%p, %v\n",n,*n)}func main() { var a N = 25 p:=&a a.Value() a.Pointer() p.Value() p.Pointer() fmt.Printf("%p, %v\n",&a,a)}
In addition, such as the dictionary itself is the pointer wrapper object, the address is not necessary to add & address characters.