doujiu5464 2012-03-18 14:15
浏览 31
已采纳

Go方法语法的基本原理

Ok, I have to admit, I don't really use Go very much at all, but I did just observe something that strikes me as odd for a language that strives for minimality and all that good stuff as Go does. I would be surprised if there isn't a legitimate rationale behind it, so that's what I'm looking for.

So when you have a method, you define it like this:

func (s *SomeStruct) Foo(x int) { }

but why have an extra parameter list just for the "receiver", as I think it's called? Would it not be a simpler and more elegant design to just do

func Foo(s *SomeStruct, x int) { }

and then have s.Foo(5) just be translated to a call to a function Foo(s, 5)?

  • 写回答

4条回答 默认 最新

  • dqcj32855 2012-03-18 19:09
    关注

    Methods are fundamentally special and different from regular functions.

    • Methods must live in the same package as the receiver type.
    • Methods are used to satisfy interfaces.
    • Receiver parameters are the only parameters which may be overloaded.
    • When anonymous struct fields have methods, those methods are "inherited".

    With your proposal, the line between a function and a method becomes very blurry and it's difficult to figure out how to resolve the above issues.

    That said, I think it would be really interesting to design a language with multimethods and interfaces. However, that language would not be Go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘