Go suggest change

Methods

A method is a function tied to a type, usually a struct but it works with any type.

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

The instance on which the method operates is called a receiver.

In the above example method PrintFullName takes a receiver p whose type is *Person.

People coming from other languages are tempted to name the receiver this (mimicking C++) or self (mimicking Python). That is bad style in Go.

In Go, the rule for naming receiver is:

Value vs. pointer receiver

Method receiver can be either a value or 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:                         0xc42000a060
PrintFullNamePointer: p is            0xc42000a060
PrintFullNameValue:   address of p is 0xc42000a080

When p is of type Person, we can call methods defined for Person and for *Person. Go automagically converts receiver Person to *Person.

It doesn’t work the other way. You can’t call method with receiver Person on value of type *Person.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents