duanfei1975 2014-04-13 15:56
浏览 120

Golang区分T和* T上的方法集的原因是什么?

This is where confuses me the most while learning go. We all know that methods on T only affect the copy of T, and methods on *T will affect the actual data on T.

Why does methods on T can also be used by *T, but the opposite is not allowed? So,can you give me an example(or reason) on why they do not allow method on *T be used by T?

What is the pros and cons of this design?

  • 写回答

3条回答 默认 最新

  • dongmu3457 2014-04-13 17:52
    关注

    You have the key to your answer in your question: methods on T only affect the copy of T. So with this information, the following excerpt from Go's FAQ should help clear the rest of the confusion:

    From the Go Spec:

    "The method set of any other named type T consists of all methods with receiver type T. The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T)."

    If an interface value contains a pointer *T, a method call can obtain a value by dereferencing the pointer, but if an interface value contains a value T, there is no useful way for a method call to obtain a pointer.

    Even in cases where the compiler could take the address of a value to pass to the method, if the method modifies the value the changes will be lost in the caller. As a common example, this code:

    var buf bytes.Buffer
    io.Copy(buf, os.Stdin)
    

    would copy standard input into a copy of buf, not into buf itself. This is almost never the desired behavior.

    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探