Golang Value receiver 和 pointer receiver

在什么情况下用 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场景:

  1. 共享receiver的变量,操作的是引用
  2. struct 非常大,用pointer recevier 性能比较好

适用value receiver场景:

  1. 是值的拷贝,没有共享变量,线程安全。

总结:

  1. Use the same receiver type for all your methods. This isn't always feasible, but try to.
  2. Methods defines a behavior of a type; if the method uses a state (updates / mutates) use pointer receiver.
  3. If a method don't mutate state, use value receiver.
  4. Functions operates on values; functions should not depend on the state of a type.

来源:https://stackoverflow.com/questions/27775376/value-receiver-vs-pointer-receiver 

发布了10 篇原创文章 · 获赞 3 · 访问量 1050

猜你喜欢

转载自blog.csdn.net/shasha6/article/details/104531675