69_Go基础_1_36 函数的值传递引用传递

 1 package main
 2 
 3 import "fmt"
 4 
 5 func fun1(num int) { // 值传递:num = a = 10
 6     fmt.Println("fun1()函数中,num的值:", num)
 7     num = 100
 8     fmt.Println("fun1()函数中修改num:", num)
 9 }
10 
11 func fun2(p1 *int) { //传递的是a的地址,就是引用传递
12     fmt.Println("fun2()函数中,p1:", *p1)
13     *p1 = 200
14     fmt.Println("fun2()函数中,修改p1:", *p1)
15 }
16 
17 func fun3(arr2 [4]int) { // 值传递
18     fmt.Println("fun3()函数中数组的:", arr2)
19     arr2[0] = 100
20     fmt.Println("fun3()函数中修改数组:", arr2)
21 }
22 
23 func fun4(p2 *[4]int) { // 引用传递
24     fmt.Println("fun4()函数中的数组指针:", p2)
25     p2[0] = 200
26     fmt.Println("fun4()函数中的数组指针:", p2)
27 }
28 
29 func main() {
30     /*
31         指针作为参数:
32 
33         参数的传递:值传递,引用传递
34     */
35 
36     a := 10
37     fmt.Println("fun1()函数调用前,a:", a) // 10
38     fun1(a)                          // 值传递,函数中修改a
39     fmt.Println("fun1()函数调用后,a:", a) // 10, 未改变
40 
41     fun2(&a)
42     fmt.Println("fun2()函数调用后,a:", a) // 200
43 
44     arr1 := [4]int{1, 2, 3, 4}
45     fmt.Println("fun3()函数调用前:", arr1) // [1 2 3 4]
46     fun3(arr1)
47     fmt.Println("fun3()函数调用后:", arr1) // [1 2 3 4]
48 
49     fun4(&arr1)
50     fmt.Println("fun4()函数调用后:", arr1) // [200 2 3 4]
51 
52 }
原文地址:https://www.cnblogs.com/luwei0915/p/15630145.html