简体   繁体   中英

What the meaning of Golang “func (t *SomeType) myFuncName(param1, param2)” syntax

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM