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.

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

报告相同问题?

悬赏问题

  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用