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!
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)
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!
If you have any mistakes or questions, please feel free to comment! !!
Recommended Posts