go语言值传递与址传递:
- 值传递是对源结构体拷贝的操作;
- 址传递是对源结构体的操作;
package main import ( "fmt" ) type BigStruct struct { C01 uint64 } func Invoke1(a *BigStruct) uint64 { a.C01++ return a.C01 } func Invoke2(a BigStruct) uint64 { a.C01++ return a.C01 } func (a *BigStruct) Invoke3() uint64 { a.C01++ return a.C01 } func (a BigStruct) Invoke4() uint64 { a.C01++ return a.C01 } func main() { var a = new(BigStruct) for i := 0; i < 3; i++ { fmt.Println("指针传递:", Invoke1(a)) } var b = BigStruct{} for i := 0; i < 3; i++ { fmt.Println("值传递:", Invoke2(b)) } var c = BigStruct{} for i := 0; i < 3; i++ { fmt.Println("指针传递:", c.Invoke3()) } var d = BigStruct{} for i := 0; i < 3; i++ { fmt.Println("值传递:", d.Invoke4()) } }
运行结果:
[ /labs02/ ] # go run labs02.go 指针传递: 1 指针传递: 2 指针传递: 3 值传递: 1 值传递: 1 值传递: 1 指针传递: 1 指针传递: 2 指针传递: 3 值传递: 1 值传递: 1 值传递: 1
参考:https://github.com/realint/labs/blob/master/src/labs02/labs02_test.go
有疑问加站长微信联系(非本文作者)