前言:关于值类型和引用类型确实是个比较绕的问题,之前在学校的时候学习C语言的时候,就感觉没有看太懂,后面看java,关于引用也是模模糊糊,这个东西也确实比较抽象,估计好多写了好几年代码的人有也有些迷惑。
a、值类型:基本数据类型,int,float,bool,string,以及数组和struct
特点:变量直接存储值,内存通常在栈中分配,栈在函数调用完会被释放
b、引用类型:指针,slice,map,chan等都是引用类型
特点:变量存储的是一个地址,这个地址存储最终的值。内存通常在堆上分配,通过GC回收。
package main
import (
"fmt"
)
//在函数内部修改值,不会影响函数外它的值,int是值类型
func swap1(a, b int) {
temp := a
a = b
b = temp
}
//可以通过返回值,实现交换
func swap2(a, b int) (c, d int) {
c = b
d = a
return c, d
}
//改变指针所指内存的值,指针是引用类型,把指针所指的值换了,可实现交换
func swap3(a, b *int) {
temp := *a
*a = *b
*b = temp
return
}
// 这样交换的是两个表示内存地址的值,也是不会影响函数外边的值的
func swap4(a, b *int) {
temp := a
a = b
b = temp
}
func main() {
first := 100
second := 200
third := 300
fourth := 400
swap1(first, second)
fmt.Println("first= ", first)
fmt.Println("second= ", second)
three, four := swap2(300, 400)
fmt.Println("third= ", three)
fmt.Println("fourth= ", four)
swap3(&first, &second)
fmt.Println("first= ", first)
fmt.Println("second= ", second)
swap4(&third, &fourth)
fmt.Println("third= ", third)
fmt.Println("fourth= ", fourth)
}
结果执行如下:
first= 100 second= 200 third= 400 fourth= 300 first= 200 second= 100 third= 300 fourth= 400
可能还是比较绕,慢慢理解吧,哈哈~~~
原文:https://www.cnblogs.com/qstudy/p/10201106.html