Essential Go  Suggest an edit

Methods

A method is a function tied to a type, most commonly a struct.

This is similar to classes in languages like Java or C++.

Basics of methods:

type Person struct {
	FirstName string
	LastName  string
}

func (p *Person) PrintFullName() {
	fmt.Printf("%s %s\n", p.FirstName, p.LastName)
}

func main() {
	p := &Person{
		"John",
		"Doe",
	}
	p.PrintFullName()
}
John Doe

In the above example method PrintFullName takes a reciver named p of type *Person.

People coming from other languages are tempted to name the receiver this (mimicking C++) or self (mimicking Python).

In Go, the rule for naming reciver is: * be short * be consistent across methods

Value vs. pointer receiver

Method receiver can be either a value and a pointer.

type Person struct {
	FirstName string
	LastName  string
}

func (p Person) PrintFullNameValue() {
	fmt.Printf("PrintFullNameValue:   address of p is %p\n", &p)
}

func (p *Person) PrintFullNamePointer() {
	fmt.Printf("PrintFullNamePointer: p is            %p\n", p)
}

func main() {
	p := Person{
		"John",
		"Doe",
	}
	fmt.Printf("address of p:                         %p\n", &p)
	p.PrintFullNamePointer()
	p.PrintFullNameValue()
}
address of p:                         0xc00000a080
PrintFullNamePointer: p is            0xc00000a080
PrintFullNameValue:   address of p is 0xc00000a0a0

As you can see, when p is of type Person, we can call both methods defined for Person and *Person. Go will automatically convert receiver Person to *Person.

It doesn’t work the other way i.e. you can’t call method with receiver Person on value with type *Person.

  ↑ ↓ to navigate     ↵ to select     Esc to close