IT评测·应用市场-qidao123.com技术社区

标题: Go语言中值接收者和指针接收者的区别? [打印本页]

作者: 鼠扑    时间: 2024-12-31 20:35
标题: Go语言中值接收者和指针接收者的区别?
在 Go 语言中,值接收者指针接收者是方法界说中的两种接收者范例。它们的主要区别在于方法调用时的举动、接收者是否可以被修改,以及性能上的差异。

值接收者

界说

值接收者的方法接收的是调用对象的一个副本,方法内部对该副本的修改不会影响原对象。
特点

示例

  1. package main
  2. import "fmt"
  3. type Rectangle struct {
  4.     Width, Height int
  5. }
  6. // 值接收者方法
  7. func (r Rectangle) Area() int {
  8.     return r.Width * r.Height
  9. }
  10. // 修改操作(仅对副本有效)
  11. func (r Rectangle) SetWidth(w int) {
  12.     r.Width = w
  13. }
  14. func main() {
  15.     rect := Rectangle{Width: 10, Height: 5}
  16.     fmt.Println("Area:", rect.Area()) // 输出: Area: 50
  17.     rect.SetWidth(20)
  18.     fmt.Println("Width after SetWidth:", rect.Width) // 输出: Width after SetWidth: 10
  19. }
复制代码
说明:调用 SetWidth 方法时,rect.Width 没有改变,因为 SetWidth 操作的是值的副本。

指针接收者

界说

指针接收者的方法接收的是调用对象的地址,方法内部对接收者的修改会直接作用于原对象。
特点

示例

  1. package main
  2. import "fmt"
  3. type Rectangle struct {
  4.     Width, Height int
  5. }
  6. // 指针接收者方法
  7. func (r *Rectangle) Scale(factor int) {
  8.     r.Width *= factor
  9.     r.Height *= factor
  10. }
  11. func main() {
  12.     rect := Rectangle{Width: 10, Height: 5}
  13.     rect.Scale(2)
  14.     fmt.Println("Scaled Width:", rect.Width) // 输出: Scaled Width: 20
  15.     fmt.Println("Scaled Height:", rect.Height) // 输出: Scaled Height: 10
  16. }
复制代码
说明:调用 Scale 方法时,rect.Width 和 rect.Height 的值被直接修改。

值接收者与指针接收者的主要区别

特性值接收者指针接收者传递内容对象的副本对象的地址方法是否能修改原对象否是适用场景- 不必要修改接收者
- 对象较小,拷贝开销小- 必要修改接收者
- 对象较大,拷贝开销大调用方式值或指针都可以调用值或指针都可以调用性能较低性能:对于大对象,会复制整个对象较高性能:传递指针,避免了对象的复制
值接收者与指针接收者的调用规则

无论方法是值接收者还是指针接收者:
示例

  1. package main
  2. import "fmt"
  3. type Counter struct {
  4.     Count int
  5. }
  6. func (c Counter) Increment() {
  7.     c.Count++
  8. }
  9. func (c *Counter) Decrement() {
  10.     c.Count--
  11. }
  12. func main() {
  13.     c := Counter{Count: 10}
  14.     // 调用值接收者方法
  15.     c.Increment()
  16.     fmt.Println("After Increment:", c.Count) // 输出: After Increment: 10 (未修改)
  17.     // 调用指针接收者方法
  18.     c.Decrement()
  19.     fmt.Println("After Decrement:", c.Count) // 输出: After Decrement: 9 (被修改)
  20. }
复制代码

如何选择值接收者或指针接收者?


示例

如果结构体实现接口时:

  1. type Resizable interface {
  2.     Resize(factor int)
  3. }
  4. type Rectangle struct {
  5.     Width, Height int
  6. }
  7. func (r *Rectangle) Resize(factor int) {
  8.     r.Width *= factor
  9.     r.Height *= factor
  10. }
复制代码

总结



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4