sajad torkamani

Define method

Go doesn’t have classes and therefore class methods. Instead, you define your methods as functions with a receiver argument.

For example, here we define a PrintDetails() method that operates on a Person receiver.

package main

import "fmt"

type Person struct {
	name string
	age  int
}

func (person Person) PrintDetails() string {
	return fmt.Sprintf("Name is %s, age is %d", person.name, person.age)
}

func main() {
	person1 := Person{name: "Bob", age: 20}
	person2 := Person{name: "Alice", age: 30}

	fmt.Println(person1.PrintDetails())
	fmt.Println(person2.PrintDetails())
}

You can only declare a method with a receiver whose type is defined in the same package as the method. You can’t declare a method with a receiver whose type is defined in another package (including the built-in types such as int).

Pointer receivers

You can declare methods with pointer receivers:

package main

import "fmt"

type Book struct {
	title string
}

func (book Book) ChangeNameV1(newTitle string) {
	book.title = newTitle
}

func (book *Book) ChangeNameV2(newTitle string) {
	book.title = newTitle
}

func main() {
	book1 := Book{title: "War and Hate"}
	book1.ChangeNameV1("Peace and Love")
	// Outputs 'War and Hate' because the receiver is a value (not a pointer)
	// and so the `ChangeNameV1` method operates on a copy of `book1`, not the
	//`book1` itself.
	fmt.Println(book1)

	book2 := Book{title: "Burger and Coke"}
	book2.ChangeNameV2("Salad and Water")

	// Outputs 'Salad and Water' because receiver is a pointer and so the
	// `ChangeNameV2` method operates on the actual value of `book2`
	fmt.Println(book2)
}

Why would you use a pointer receiver?

  1. If your method needs to modify the value itself, not a copy of it.
  2. To avoid copying the value on each method call. More efficient if the receiver is a large struct, for example.
Tagged: Golang