-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstruct_pointer.go
More file actions
126 lines (111 loc) · 1.85 KB
/
struct_pointer.go
File metadata and controls
126 lines (111 loc) · 1.85 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"fmt"
"reflect"
)
type A struct {
int64
}
type B struct {
F float64
S string
A
}
type C struct {
bool
*B
}
type D struct {
a int
b *string
c string
}
type E struct {
a *int
b string
c *string
}
type Scope struct {
Type int
IDs []int64
Ext []string
}
func TestStructWithAnonymousField() {
c := C{
bool: false,
B: &B{
F: 1.64,
S: "testStruct",
A: A{
int64: 12345,
},
},
}
fmt.Println(c.bool, c.B, c.F, c.S, c.A, c.int64) // 没有变量名的直接用类型名代替
c.A = A{int64: 54321}
fmt.Println(c.bool, c.B, c.F, c.S, c.A, c.int64) // 修改成功
}
func TestModifyFieldWithPointerOrNot() {
a1 := A{int64(2)}
a2 := A{int64(2)}
modifyFieldWithPointerOrNot(a1, &a2)
fmt.Println("ModifyFieldWithoutPointer: ", a1)
fmt.Println("ModifyFieldWithPointer: ", a2)
}
func modifyFieldWithPointerOrNot(a A, ap *A) {
a.int64 += 1
ap.int64 += 1
}
func (a *A) add(i int64) {
a.int64 += i
}
func addFunc(a *A, i int64) {
a.int64 += i
}
func TestCallMethodAndFuncWithPointerOrNot() {
a := A{int64(2)}
// 编译错误
// addFunc(a, 2)
// 下面都编译成功
addFunc(&a, 2)
fmt.Println(a)
a.add(2)
fmt.Println(a)
(&a).add(2)
fmt.Println(a)
}
func TestFieldEmptyWithPointer() {
d := D{
a: 0,
c: "",
}
e := E{
a: &d.a,
b: *d.b,
c: &d.c,
}
fmt.Println(d)
fmt.Println(e)
}
func TestDeepEqual() {
var (
scopes1 = make(map[int]Scope)
scopes2 = make(map[int]Scope)
ext1 = make(map[string]interface{})
ext2 = make(map[string]interface{})
)
scopes1[1] = Scope{
Type: 1,
IDs: []int64{2, 3, 4},
Ext: []string{"2", "3", "4"},
}
scopes2[1] = Scope{
Type: 1,
IDs: []int64{2, 3, 4},
Ext: []string{"2", "3", "4"},
}
ext1["12312321"] = scopes1
ext2["12312321"] = scopes2
fmt.Println(reflect.DeepEqual(scopes1, scopes2))
fmt.Println(reflect.DeepEqual(ext1, ext2))
}