[Golang] Basics of Go language About value receiver and pointer receiver

This time we'll talk about Go language value receivers and pointer receivers! After this article, please read this article to get a better understanding of the Go language!

What is a value receiver?


package main

import "fmt"

type Vertex struct {
	X, Y int
}

func (v Vertex) Area() int {
	return v.X * v.Y
}

//Value receiver
func (v Vertex) Scale(i int) {
	v.X = v.X * i
	v.Y = v.Y * i
}

func main() {
	v := Vertex{3, 4}
	v.Scale(10)
	fmt.Println(v.Area()) // => 12
}

This is the value receiver. Roughly speaking, if there is no *, it will be a value receiver. It seems to be called passing by value.

The argument is passed in v.Scale (10), and ** v.X = 3 * 10 v.Y = 4 * 10 ** in the Scale function. However, you cannot directly rewrite the contents of Vertex by passing by value. The value was just rewritten within the scope of the Scale function. Therefore, since the initial values X and Y are used in the Area function, 3 * 4 = 12 is output as the return value.

[Supplement] You can associate ** Vertex with the Area () function by writing ** func (v Vertex) Area () **. ** ** When calling this method, you can call it by writing ** v.Area () **. Go doesn't have the concept of a class, but it allows you to write it in an object-oriented way. (It's like User.hoge in ruby)

Value receiver


package main

import "fmt"

type Vertex struct {
	X, Y int
}

func (v Vertex) Area() int {
	return v.X * v.Y
}

//Pointer receiver(*Just got it)
func (v *Vertex) Scale(i int) {
	v.X = v.X * i
	v.Y = v.Y * i
}

func main() {
	v := Vertex{3, 4}
	v.Scale(10)
	fmt.Println(v.Area()) // => 1200
}

I just added * next to the variable name! By doing this, you can rewrite the contents of the structure.

Therefore, when passed as an argument of the Scale function, ** v.X = 30, v.Y = 40 **, which is passed to the Area function as it is.

Therefore, the output result of v.Area () is 1200!

Thank you for reading to the end!

If you have any mistakes or questions, please feel free to comment! !!

Recommended Posts

[Golang] Basics of Go language About value receiver and pointer receiver
[Golang] About Go language Producer and Consumer
[Golang] About Go language channel
[Golang] Go language basics What is Goroutine?
Features of Go language
About the return value of pthread_mutex_init ()
About the return value of the histogram.
About the basics list of Python basics
I made go language for api and minimum configuration of react for front
Answers and impressions of 100 language processing knocks-Part 1
About sensor_mode and angle of view of picamera
[MacOS] Installation of Go (Go language) using goenv
[Python] Chapter 02-04 Basics of Python Program (About Comments)
I compared the speed of go language web framework echo and python web framework flask
[Basics of modern mathematical statistics with python] Chapter 2: Probability distribution and expected value