douershuang7356 2018-11-20 06:18
浏览 50
已采纳

在结构定义之外使用方法的原因是什么?

Why do we have the methods declared outside the type definition of the struct? E.g.:

type antenna struct {
    name string
    length float32
    girth float32
    bloodtype string
}

func (p *antenna) extend() {
    p.length += 10
}

It seems to me that the method could be part of the struct? (Let's ignore for now that structs are supposed to be value types)

type antenna struct {
    name string
    length float32
    girth float32
    bloodtype string

    func extend() {
        length += 10
    }
}

This would be more similar to traditional OOP. I didn't find any good explanations of why it is done the way it is besides "structs are value-types and classes are reference-types". I know the difference, but it's not a satisfactory answer to me. In any way the method has to be called like this:

var x = antenna()
x.extend() 

So what's the point of separating the the struct and methods? Having them visually grouped together in the code - as in typical OOP languages - seems useful to me?

  • 写回答

2条回答 默认 最新

  • duanfu5239 2018-11-20 06:40
    关注

    My Viewpoints:
    1. It is simpler this way and makes language consistent/uniform for struct types and other types like following code.
    2. You don't need this or self pointer to use and you name it as you wish, and this makes it even simpler to explain what is p (in your example).

    Also may be this is relevant:
    In Go is naming the receiver variable 'self' misleading or good practice?

    You may define your own types, See this sample (There is no inside or struct here for this named type):

    package main
    
    import "fmt"
    
    type num int32
    
    func (p *num) inc() {
        *p++
    }
    
    func main() {
        p := num(100)
        p.inc()
        fmt.Println(p) // 101
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能