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条)

报告相同问题?

悬赏问题

  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办