整形:值传递
package main

import "fmt"

func Swap(num1, num2 int) {
	num1, num2 = num2, num1
	fmt.Println(num1, num2)
}
func main() {
	num1 := 10
	num2 := 20
	Swap(num1, num2)
	fmt.Println(num1, num2)
}

Go基础:不同数据类型作为函数参数传递值传递/地址(引用)传递判断_指针变量

字符串:值传递
package main

import "fmt"

func Swap(s1, s2 string) {
	s1, s2 = s2, s1
	fmt.Println(s1, s2)
}
func main() {
	s1 := "aaaaaaa"
	s2 := "bbbbbbb"
	Swap(s1, s2)
	fmt.Println(s1, s2)
}

Go基础:不同数据类型作为函数参数传递值传递/地址(引用)传递判断_数组_02

数组:值传递
package main

import "fmt"

func Swap(array [3]int) {
	array[0] = 0
	array[1] = 1
	array[2] = 2
	fmt.Println(array)
}
func main() {
	array := [3]int{8, 8, 8}
	Swap(array)
	fmt.Println(array)
}

Go基础:不同数据类型作为函数参数传递值传递/地址(引用)传递判断_指针变量_03

切片:地址传递
package main

import "fmt"

func Swap(slice []int) {
	slice[0] = 0
	slice[1] = 1
	slice[2] = 2
	fmt.Println(slice)
}
func AppendTest(slice []int) {
	slice = append(slice, 4)
}
func AppendTest1(slice []int) []int {
	slice = append(slice, 4)
	return slice
}
func main() {
	slice := []int{8, 8, 8}
	Swap(slice)
	fmt.Println(slice)
	AppendTest(slice)
	fmt.Println(slice)
	slice = AppendTest1(slice)
	fmt.Println(slice)
}

Go基础:不同数据类型作为函数参数传递值传递/地址(引用)传递判断_数组_04

注意:如果在调用的函数中,原始切片的容量发生了改变,系统就会在新的地址生成新的切片,原始切片不会发生变化。

map:地址传递
package main

import "fmt"

func test(m map[int]string){
	delete(m,1)
}

func main(){
	m := map[int]string{1:"make",2:"Go"}
	test(m)
	fmt.Println(m)
}

Go基础:不同数据类型作为函数参数传递值传递/地址(引用)传递判断_运算符_05

结构体:值传递
package main

import "fmt"

type Student struct {
	id   int
	name string
}

func test(stu Student) {
	stu.id = 2
	stu.name = "李四"
	fmt.Println(stu)
}

func main() {
	stu := Student{1, "张三"}
	test(stu)
	fmt.Println(stu)
}

Go基础:不同数据类型作为函数参数传递值传递/地址(引用)传递判断_数组_06

指针:地址传递


&变量 取地址操作 引用运算符

*指针变量 取值操作 解引用运算符

package main

import "fmt"

type Student struct {
	id   int
	name string
}

func Swap(num1, num2 *int) {
	*num1, *num2 = *num2, *num1
	fmt.Println(*num1, *num2)
}

func main() {
	a := 10
	b := 20
	c := &a
	d := &b
	Swap(c, d)
	fmt.Println(*c, *d)
}

Go基础:不同数据类型作为函数参数传递值传递/地址(引用)传递判断_值传递_07