dongqigu0429 2015-04-05 19:17
浏览 45
已采纳

指针和值接收器类型之间有什么区别?

I was writing a program that reads data from a io.Reader and caches them in a bytes.Buffer.

type SecureReader struct {
    pipe      io.Reader
    shared    *[32]byte
    decrypted bytes.Buffer
}

func (s SecureReader) Read(b []byte) (int, error) {
    s.decryptPipeIntoBuffer()
    return s.decrypted.Read(b)
}

func (s SecureReader) decryptPipeIntoBuffer() (int, error) {/*Lots of code...*/}

I first used a value receiver, because I thought they were the same. However, I noticed my method does not do anything when invoked: SecureReader.Read() would always return io.EOF.

I banged my head around and changed the receiver type to

func (s *SecureReader) decryptPipeIntoBuffer() (int, error) {/*Lots of code...*/}

Now my code magically works. What is going on?

  • 写回答

1条回答 默认 最新

  • doutang6819 2015-04-05 19:22
    关注

    A value receiver operates on a copy of the SecureReader instance s.

    If the method mutates any part of the copy of the instance (like modify s.decrypted), it is not visible on the original instance of the receiver, once the method exit.

    That changes with a pointer receiver, where the method operates and can mutates the actual SecureReader instance s, since a copy of the pointer is passed to the method.


    See more examples in "Don't Get Bitten by Pointer vs Non-Pointer Method Receivers in Golang".

    Simply stated: you can treat the receiver as if it was an argument being passed to the method. All the same reasons why you might want to pass by value or pass by reference apply.

    Reasons why you would want to pass by reference as opposed to by value:

    • You want to actually modify the receiver (“read/write” as opposed to just “read”)
    • The struct is very large and a deep copy is expensive
    • Consistency: if some of the methods on the struct have pointer receivers, the rest should too. This allows predictability of behavior

    If you need these characteristics on your method call, use a pointer receiver.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题