在什么情况下用 value receiver 什么情况下用 pointer receiver
type T struct {
a int
}
func (tv T) Mv(a int) int { return 0 } // value receiver
func (tp *T) Mp(a int) int { return 1 } // pointer receiver
receiver 类型是基础类型,例如slices, and small structs等值传递是更高效。very cheap so unless the semantics of the method requires a pointer, a value receiver is efficient and clear."
有如下性能测试
// Struct one empty string property
BenchmarkChangePointerReceiver 2000000000 0.36 ns/op
BenchmarkChangeItValueReceiver 500000000 3.62 ns/op
// Struct one zero int property
BenchmarkChangePointerReceiver 2000000000 0.36 ns/op
BenchmarkChangeItValueReceiver 2000000000 0.36 ns/op
两者区别与总结
适用pointer receiver场景:
- 共享receiver的变量,操作的是引用
- struct 非常大,用pointer recevier 性能比较好
适用value receiver场景:
- 是值的拷贝,没有共享变量,线程安全。
总结:
- Use the same receiver type for all your methods. This isn't always feasible, but try to.
- Methods defines a behavior of a type; if the method uses a state (updates / mutates) use pointer receiver.
- If a method don't mutate state, use value receiver.
- Functions operates on values; functions should not depend on the state of a type.
来源:https://stackoverflow.com/questions/27775376/value-receiver-vs-pointer-receiver