【Go】指针
值传递
1
2
3
4
5
6
7// 值传递
func swap1(a int, b int) {
var temp int
temp = a
a = b
b = temp
}引用传递
1
2
3
4
5
6
7// 引用传递
func swap2(pa *int, pb *int) {
var temp int
temp = *pa
*pa = *pb
*pb = temp
}测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21func main() {
var a int = 10
var b int = 20
// swap前
fmt.Println("----初始值----")
fmt.Println("a = ", a)
fmt.Println("b = ", b)
// 值传递后
fmt.Println("----值传递后----")
swap1(a, b)
fmt.Println("a = ", a)
fmt.Println("b = ", b)
// 引用传递后
fmt.Println("----引用传递后----")
swap2(&a, &b)
fmt.Println("a = ", a)
fmt.Println("b = ", b)
}测试结果