-
Notifications
You must be signed in to change notification settings - Fork 0
/
019.struct.go
70 lines (57 loc) · 1.58 KB
/
019.struct.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
package main
import (
"fmt"
)
// Go 語言沒有 class,要自定義變數的集合只有 struct,而且方法不能寫在原本的 scope 內,要另外寫。
type Cat struct {
name string
age int
weight int
color string
}
func (c *Cat) Bark() string {
return "Meow"
}
func (c *Cat) GetAge() int {
return c.age
}
func (c Cat) GetWeight() int {
return c.weight
}
// 這個不能改變 weight
func (c Cat) SetWeightByValueMethod(weight int) {
c.weight = weight
}
// 這個才可以改變 weight
func (c *Cat) SetWeightByPointerMethod(weight int) {
c.weight = weight
}
// 參考
// https://golang.org/doc/faq#methods_on_values_or_pointers
func (c Cat) GetColor() string {
return c.color
}
func main() {
var firstCat Cat = Cat{name: "firstCat", age: 2, weight: 5, color: "Black"}
fmt.Println("I'm", firstCat)
fmt.Println(firstCat.Bark())
fmt.Printf("I'm %d years old.\n", firstCat.GetAge())
fmt.Printf("My skin color is %s .\n", firstCat.GetColor())
// Demo different set method between ByValue and ByPointer.
fmt.Printf("My body weight is %d kg .\n", firstCat.GetWeight())
firstCat.SetWeightByValueMethod(7)
fmt.Printf("My body weight is %d kg .\n", firstCat.GetWeight())
firstCat.SetWeightByPointerMethod(7)
fmt.Printf("My body weight is %d kg .\n", firstCat.GetWeight())
//copy struct
copyCat := Cat(firstCat)
fmt.Println("firstCat:", firstCat)
fmt.Println("copyCat:", copyCat)
fmt.Println("Is copyCat == firstCat ?", copyCat == firstCat)
// Anonymous Struct
anonymousStruct := struct {
Name string
age int
}{Name: "aa", age: -1}
fmt.Println(anonymousStruct)
}