-
Notifications
You must be signed in to change notification settings - Fork 0
/
07-indirection-values.go
43 lines (36 loc) · 995 Bytes
/
07-indirection-values.go
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func AbsFunc(v Vertex) float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := Vertex{3, 4}
// This calls the Abs() method bound to the Vertex struct
// The Abs() method has a value receiver, not a pointer receiver
fmt.Println(v.Abs())
fmt.Println(AbsFunc(v)) // AbsFunc is a function that takes a value
p := &Vertex{4, 3}
fmt.Println(p.Abs())
fmt.Println(AbsFunc(*p))
}
// Functions that take a value argument must take a value of that specific type:
//
// var v Vertex
// fmt.Println(AbsFunc(v)) // OK
// fmt.Println(AbsFunc(&v)) // Compile error!
// while methods with value receivers take either a value or a pointer as the receiver when they are called:
//
// var v Vertex
// fmt.Println(v.Abs()) // OK
// p := &v
// fmt.Println(p.Abs()) // OK
// In this case, the method call p.Abs() is interpreted as (*p).Abs().