Contents

Go Method

What is mean of Method?

The Method means a function of a class in OOP.

Value vs Pointer receiver

There are two ways to receive the structure.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

type Rect struct {
	width, height int
}

// Value receiver
func (r Rect) areaWithValue() int {
	r.width++
	return r.width * r.height
}

// Pointer receiver
func (r *Rect) areaWithPointer() int {
	r.width++
	return r.width * r.height
}

func main() {
	rect := Rect{10, 20}
	println(rect.areaWithValue())   // 220
	println(rect.width)             // 10
	println(rect.areaWithPointer()) // 220
	println(rect.width)             // 11
}