Golang is a pass by value language, so any time we pass a value to a function either as a receiver or as an argument that data is copied in memory and so the function by default is always going to be working on a copy of our data structure. We can address this problem and modify the actual underlying data structure through the use of pointers and memory address.
值类型
先来看一段代码:
package main
import (
"fmt"
)
type person struct {
name string
}
func (p person) print() {
fmt.Printf("%+v", p)
}
func (p person) updateName(newName string) {
p.name = newName
}
func main() {
jim := person{name: "Jim"}
jim.updateName("Jimmy")
jim.print()
}
运行结果:
{name:Jim}
没有达到我们期待的结果:
{name:Jimmy}
值传递意味着每当我们将某个值传递给函数时,golang 就会取那个值或那个结构。
为了达到我们的预期,修改源代码:
package main
import (
"fmt"
)
type person struct {
name string
}
func (p person) print() {
fmt.Printf("%+v", p)
}
func (pointerToPerson *person) updateName(newName string) {
(*pointerToPerson).name = newName
}
func main() {
jim := person{name: "Jim"}
jimPointer := &jim
jimPointer.updateName("Jimmy")
jim.print()
}
运行结果:
{name:Jimmy}
最后一点,小的改进:
func main() {
jim := person{name: "Jim"}
jim.updateName("Jimmy")
jim.print()
}
pointer shortcut, go will automatically turn your variable of type person into pointer person for you.
引用类型
先看一段代码:
package main
import "fmt"
func updateSlice(s []string) {
s[0] = "Bye"
}
func main() {
mySlice := []string{"Hi", "There", "how", "are", "you?"}
updateSlice(mySlice)
fmt.Println(mySlice)
}
运行结果:
[Bye There how are you?]
运行结果为什么是这样?
When we make the slice of string golang internally is creating two separate data structures. What we call a function and pass my slice into it, golang is still behaving as a pass by value language. Even though the slice data structure is copied it is still pointing at the original array in memory, because the slice data structure and the array data structure are two separate elements in memory.
总结
Whenever you pass an integer, float, string, or struct into a function, golang will creates a copy of each argument, and these copies are used inside of the function.