douxinghuai3150 2016-03-29 19:40 采纳率: 0%
浏览 172
已采纳

为什么Go中的方法只能在同一包中定义的类型上声明?

The Go Tour says the following:

You can only declare a method with a receiver whose type is defined in the same package as the method. You cannot declare a method with a receiver whose type is defined in another package (which includes the built-in types such as int).

Is there a reason for this other than avoiding everyone building their own methods off int and string? I've Googled around, but can't find anything referencing it.

  • 写回答

1条回答 默认 最新

  • douzhun4124 2016-03-29 19:51
    关注

    The reason is that if you could define methods on other packages' types, you could modify the behavior of other packages. This is because the method set of a given type can have an effect on how values of that type are used.

    Consider, for example, the fmt.Println function. When you pass an argument to fmt.Println, it will print a string representation of that value based on a set of rules. One of those rules is that if the type of the value has a String() string method (that is, it implements the fmt.Stringer interface), then that method will be called in order to obtain the string representation of the value.

    Thus, imagine that we have a package, foo, and that package has a type, FooInt, defined as follows:

    type FooInt int
    

    Now imagine that this package also has a function, PrintFooInt:

    func PrintFooInt(f FooInt) { fmt.Println(f) }
    

    This will print the integer value of f. But let's say that you (in a different package, say main) were able to add methods to FooInt. Then you could do this:

    func (f FooInt) String() string { return "foobar!" }
    

    This would actually change the behavior of foo.PrintFooInt, which shouldn't be possible from outside the package.

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

报告相同问题?

悬赏问题

  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符