-5

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.

  • 3
    `myFuncName` is called a *method* and you can find information about them here: https://tour.golang.org/methods/1 – Ray Toal Feb 04 '18 at 08:18
  • 2
    `t *SomeType` is called the method receiver. This means that `myFuncName` is a method on `SomeType`. Please take the Go tour, this is covered in the section linked to by @RayToal – Marc Feb 04 '18 at 08:22
  • If you're studying the language, it's worth (repeatedly) slogging through the official language specification, even though it's dense and takes a while. – jrefior Feb 04 '18 at 08:26
  • 1
    Ray Toal - Thank You! So they (golang creators) have scrambled all the definitions - "methods" in programming are belong to class - while functions to the scope. No wonder it's hard to find information. – Sergo Kalandadze Feb 04 '18 at 09:09
  • 1
    Nobody scrambled anything. Methods do not belong to classes. That's just how some languages use them. – Jonathan Hall Feb 04 '18 at 09:32
  • Flimzy - even if "special methods" may be used in the language specific way - it's not make it easier to come to the proper definition - while writing something called "func" to the scope. – Sergo Kalandadze Feb 04 '18 at 09:40
  • (t *SomeType) is a method receiver. Since it is of pointer to struct `SomeType`. You needs to call method `myFuncName` using receiver. We can use method receivers as pointer in case we wants to point to variable which is struct having values assigned like pointer to database connection. – Himanshu Feb 04 '18 at 10:03
  • Marc, Himanshu - Thank You both very much - the matter is clear for me now. – Sergo Kalandadze Feb 04 '18 at 11:14
  • 1
    Does this answer your question? [Function declaration syntax: things in parenthesis before function name](https://stackoverflow.com/questions/34031801/function-declaration-syntax-things-in-parenthesis-before-function-name) – Michael Freidgeim Mar 12 '21 at 22:01

1 Answers1

3

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.

jrefior
  • 4,092
  • 1
  • 19
  • 29