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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • 普通网友 2018-11-20 07:09
    关注

    In golang, if we need a function associated with a type (say struct), then it must be defined as below (here is for go struct):

    type my_type struct {
        // fields ...
    }
    
    func (m my_type) fn_name(fn_parameters) fn_return_type {
        // do whatever we want
    }
    

    It's not something you define in your own way. But the identifier's names can be used as we want.

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 multisim电路设计(相关搜索:设计报告)
  • ¥15 从github上下载的项目到ecplise上咋运行
  • ¥15 PC-lint Plus
  • ¥15 gpl24676注释
  • ¥15 php5.3内存泄露
  • ¥15 DigSilent如何复制复合模型到自己案例?
  • ¥15 求日版华为b610s-77a 官方公版固件,有偿
  • ¥15 关于#java#的问题,请各位专家解答!(相关搜索:java程序)
  • ¥15 linux tsi721的驱动编译后 insmod 提示 报错
  • ¥20 multisim测数据