func cal (num1 int, num2 int){//注意,此处省略了返回列表的()fmt.Println(num1 + num2)}funcmain(){cal(10,20)}``````````````````````````````````````````````````````````````````````````````````````````````````(base) PS E:\Goproject\src\gocode\testproject01\unit2\demo01>go run .\main.go3``````````````````````````````````````````````````````````````````````````````````````````````````
3、多个返回值的情况
func cal (num1 int, num2 int)(addRes int, subRes int){// 函数返回只有一个的情况下,可以省略()addRes = num1 + num2subRes = num1 - num2return addRes, subRes
}funcmain(){addRes, subRes :=cal(10,20)//返回多少个值就用多少个变量接收//如果不需要某个返回值,用 "_" 接收进行忽略//如 addRes, _ := cal(10, 20)fmt.Printf("add result is %d, sub result is %d", addRes, subRes)}``````````````````````````````````````````````````````````````````````````````````````````````````(base) PS E:\Goproject\src\gocode\testproject01\unit2\demo01>go run .\main.go
add result is 30, sub result is -10``````````````````````````````````````````````````````````````````````````````````````````````````
4、 每个函数执行程序会给这个函数会单独开辟一个内存空间,所以涉及到数值交换的情况下传入地址
// 函数执行完毕之后所对应的内存空间会销毁//a、 不传入变量地址的情况func swap (num1 int, num2 int){// 函数返回只有一个的情况下,可以省略()num1, num2 = num2, num1
}funcmain(){a :=1b :=2fmt.Printf("before change, a is %d, b is %d \n", a, b)swap(a, b)fmt.Printf("after change, a is %d, b is %d", a, b)}``````````````````````````````````````````````````````````````````````````````````````````````````(base) PS E:\Goproject\src\gocode\testproject01\unit2\demo01>go run .\main.go
before change, a is 1, b is 2
after change, a is 1, b is 2``````````````````````````````````````````````````````````````````````````````````````````````````//b、 传入变量地址的情况func swap (num1 *int, num2 *int){// 函数返回只有一个的情况下,可以省略()*num1,*num2 =*num2,*num1
}funcmain(){a :=1b :=2fmt.Printf("before change, a is %d, b is %d \n", a, b)swap(&a,&b)fmt.Printf("after change, a is %d, b is %d", a, b)}``````````````````````````````````````````````````````````````````````````````````````````````````(base) PS E:\Goproject\src\gocode\testproject01\unit2\demo01>go run .\main.go
before change, a is 1, b is 2
after change, a is 2, b is 1``````````````````````````````````````````````````````````````````````````````````````````````````