dsnw2651 2018-05-14 14:58
浏览 105

golang和指针接收器中的自定义错误

Reading about value receivers vs pointer receivers across the web and stackoverflow, I understand the basic rule to be: If you don't plan to modify the receiver, and the receiver is relatively small, there is no need for pointers.

Then, reading about implementing the error interface (eg. https://blog.golang.org/error-handling-and-go), I see that examples of the Error() function all use pointer receiver.

Yet, we are not modifying the receiver, and the struct is very small.

I feel like the code is much nicer without pointers (return &appError{} vs return appError{}).

Is there a reason why the examples are using pointers?

  • 写回答

5条回答 默认 最新

  • duan_88598 2018-05-14 15:05
    关注

    No :)

    https://blog.golang.org/error-handling-and-go#TOC_2.

    Go interfaces allow for anything that complies with the error interface to be handled by code expecting error

    type error interface {
        Error() string
    }
    

    Like you mentioned, If you don't plan to modify state there is little incentive to pass around pointers:

    • allocating to heap
    • GC pressure
    • Mutable state and concurrency, etc

    On a random rant , Anecdotally, I personally think that seeing examples like this one are why new go programers favor pointer receivers by default.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100