duanhe0817825 2018-02-04 08:14 采纳率: 100%
浏览 488

Golang“ func(t * SomeType)myFuncName(param1,param2)”语法的含义是什么

I am studying Golang - in tutorials I often see syntax like this:

type SomeType struct {

      //struct entries

}

Following by:

func (t *SomeType) myFuncName(param1, param2) typeToReturn {

     //function body and return

}

Please explain what pointer to the struct (t *SomeType) does there - why it is needed and what is the correct name for this syntax - for it was impossible to find explanation in the official documentation.

  • 写回答

1条回答 默认 最新

  • douyuliu9527 2018-02-04 08:24
    关注

    That's a type definition followed by a method function definition with a pointer receiver of the defined type. See the Go Language Specification on Method Sets.

    So

    package main
    
    import(
        "fmt"
    )
    
    type TD struct {
        Foo     string
    }
    
    func (td *TD) Bar() {
        td.Foo = `bar`
    }
    
    func main() {
        a := new(TD)
        a.Bar()
        fmt.Println(a.Foo)
    }
    

    prints bar

    It's somewhat similar to a class definition followed by a method definition in some other languages.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器