简单聊聊值类型引用类型
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 | package main |