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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line