Func (r receiver) identifier(parameters) (return(s)){...}

package main

import "fmt"

type person struct {
	first string
	last  string
}

type secretAgent struct {
	person
	ltk bool
}

//func (r receiver) identifier(parameters) (return(s)){...}

func (s secretAgent) speak() {
	fmt.Println("I am", s.first, s.last)

}

func main() {
	sa1 := secretAgent{
		person: person{
			first: "James",
			last:  "Bond",
		},
		ltk: true,
	}

	fmt.Println(sa1)

	sa1.speak()

}

I am aware that the receiver spot makes it so only those of that type have access to this function… in this case those with the type of secretAgent, but what does the s next to it mean? is that the equivalent to a parameter inside of the func speak()

The receiver is specified using 2 identifiers, the first specifies its name that is used within the methods body, the second specifies its type.

It is very similar to a regular function argument, with the exception, that there can only be a single receiver.

s is like this in classic OOP languages. When your method is called, s contains the ‘object’ that it was called through, in your case it will contain what is known as sa1 in main. It’s as if you defined

func speak(s secretAgent) { ...}

and called it like

  speak(sa1)
2 Likes

Awesome great analogy. I come from a JavaScript background so that really clicked.