简单聊聊值类型引用类型

With ‘value types’ in Go, do we have to worry about pointers if we want to pass a value to a function and modify the original value inside the function?

With ‘reference types’ in Go, do we have to worry about pointers if we want to pass a value to a function and modify the original value inside the function?

背景

总结 Udemy 上 Golang 入门课程再次学习
这个购买于当初尝试入门 Golang 语言的时候
现在以相对已经熟悉 Golang 语言的知识储备来进行复盘学习

Go 语言中的值类型函数参数需要担心原始数据被修改

WHAT: 哪些类型属于值类型

  • int
  • float
  • string,
  • bool
  • structs

HOW: 怎么更容易理解这个概念

最清晰的方法之一:

struct 实例(instance)的 method receiver 是 pointer 的话实例可被修改, 是 value 的话会被浅拷贝

Go 语言中的引用类型函数参数不需要考虑原始数据被修改

WAHT: 哪些类型属于引用类型

  • slices
  • maps
  • channels
  • pointers
  • functions

HOW: 怎么更容易理解这个概念

Pointer 我们可修改,Pointer 的 Pointer 我们修改的是在当前上下文新建的值,而修改不了原始数据

Take is cheap, show me the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import "log"

// 严重那种值类型能被函数修改到

func main() {
vType := 0 // 值类型
rType := &struct {
Value int
}{Value: 0} // 引用类型, 指针类型

ModifyVType(&vType)
ModifyRType(&rType) // Pointer's pointer can't chang original value

log.Println("vType", vType)
log.Println("rType", rType)
}

func ModifyRType(i **struct{ Value int }) {
newOne := &struct {
Value int
}{Value: 0}
i = &newOne
}

func ModifyVType(i *int) {
*i = 1
}