-
Notifications
You must be signed in to change notification settings - Fork 2
/
example3.go
99 lines (72 loc) · 2.18 KB
/
example3.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright 2014 Ardan Studios
//
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program to show how to declare function variables.
package main
import "fmt"
// data is a struct to bind methods to.
type data struct {
name string
age int
}
// displayName provides a pretty print view of the name.
func (d data) displayName() {
fmt.Println("My Name Is", d.name)
}
// setAge sets the age and displays the value.
func (d *data) setAge(age int) {
d.age = age
fmt.Println(d.name, "Is Age", d.age)
}
func main() {
// Declare a variable of type data.
d := data{
name: "Bill",
}
fmt.Println("Proper Calls to Methods:")
// How we actually call methods in Go.
d.displayName()
d.setAge(45)
fmt.Println("\nWhat the Compiler is Doing:")
// This is what Go is doing underneath.
data.displayName(d)
(*data).setAge(&d, 45)
// =========================================================================
fmt.Println("\nCall Value Receiver Methods with Variable:")
// Declare a function variable for the method bound to the d variable.
// The function variable will get its own copy of d because the method
// is using a value receiver.
f1 := d.displayName
// Call the method via the variable.
f1()
// Change the value of d.
d.name = "Joan"
// Call the method via the variable. We don't see the change.
f1()
// =========================================================================
fmt.Println("\nCall Pointer Receiver Method with Variable:")
// Declare a function variable for the method bound to the d variable.
// The function variable will get the address of d because the method
// is using a pointer receiver.
f2 := d.setAge
// Call the method via the variable.
f2(45)
// Change the value of d.
d.name = "Sammy"
// Call the method via the variable. We see the change.
f2(45)
}
// Outputs:
// Proper Calls to Methods:
// My Name Is Bill
// Bill Is Age 45
// What the Compiler is Doing:
// My Name Is Bill
// Bill Is Age 45
// Call Value Receiver Methods with Variable:
// My Name Is Bill
// My Name Is Bill
// Call Pointer Receiver Method with Variable:
// Joan Is Age 45
// Sammy Is Age 45