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 51寻迹小车定点寻迹
  • ¥15 爬虫爬取网站的一些信息
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件