Go : 指针作为参数

Go : 指针作为参数

package main

import "fmt"

//指针作为参数
func main() {
	a := 10
	fmt.Println("fun1()函数调用前,a:",a)   //10
	fun1(a)
	fmt.Println("fun1()函数调用后,a:",a)   //10
	fun2(&a)
	fmt.Println("fun2()函数调用后,a: ",a)  //200
	arr1 := [4]int{1,2,3,4}
	fmt.Println("fun3()函数调用前,arr1:",arr1)
	fun3(arr1)
	fmt.Println("fun3()函数调用后,arr1:",arr1)
	fun4(&arr1)
	fmt.Println("fun4()函数调用后,arr1:",arr1)
}
func fun1(num int) {    //值传递
	fmt.Println("fun1()函数中,num的值: ",num)  //10
	num = 100
	fmt.Println("fun1()函数中修改num: ",num)   //100
}
func fun2(p1 *int) {   //引用传递 , 传递的是a的地址
	fmt.Println("fun2()函数中,p1: ",*p1)   //10
	*p1 = 200
	fmt.Println("fun2()函数中,修改后p1:",*p1)  //200
}
func fun3(arr2 [4]int) {    //值传递
	fmt.Println("fun3()函数中的数组:",arr2)
	arr2[0] = 100
	fmt.Println("fun3()函数修改后数组:",arr2)
}
func fun4(p2 *[4]int) {    //引用传递
	fmt.Println("fun4()函数中的数组:",p2)
	p2[0] = 200
	fmt.Println("fun4()函数中,修改后的数组:",p2)

结果:

fun1()函数调用前,a: 10
fun1()函数中,num的值:  10
fun1()函数中修改num:  100
fun1()函数调用后,a: 10
fun2()函数中,p1:  10
fun2()函数中,修改后p1: 200
fun2()函数调用后,a:  200
fun3()函数调用前,arr1: [1 2 3 4]
fun3()函数中的数组: [1 2 3 4]
fun3()函数修改后数组: [100 2 3 4]
fun3()函数调用后,arr1: [1 2 3 4]
fun4()函数中的数组: &[1 2 3 4]
fun4()函数中,修改后的数组: [200 2 3 4]
fun4()函数调用后,arr1: [200 2 3 4]
posted @ 2020-05-05 22:15  MrSunday  阅读(184)  评论(0)    收藏  举报