Skip to content

Instantly share code, notes, and snippets.

@guerbai
Created June 3, 2019 03:44
Show Gist options
  • Save guerbai/e32456611912aaf7649e700f17128017 to your computer and use it in GitHub Desktop.
Save guerbai/e32456611912aaf7649e700f17128017 to your computer and use it in GitHub Desktop.
是否修改数据的值
// 传址会修改原数据
func main() {
x := [3]int{1,2,3}
func(arr *[3]int) {
(*arr)[0] = 7
fmt.Println(arr) // &[7 2 3]
}(&x)
fmt.Println(x) // [7 2 3]
}
// 数组使用值拷贝传参
func main() {
x := [3]int{1,2,3}
func(arr [3]int) {
arr[0] = 7
fmt.Println(arr) // [7 2 3]
}(x)
fmt.Println(x) // [1 2 3] // 并不是你以为的 [7 2 3]
}
// 会修改 slice 的底层 array,从而修改 slice
func main() {
x := []int{1, 2, 3}
func(arr []int) {
arr[0] = 7
fmt.Println(x) // [7 2 3]
}(x)
fmt.Println(x) // [7 2 3]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment