虽然go语言中函数传参方式都是值传递,但以下几种类型可以认为是"引用传递"。
关键词:golang
切片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package main
import "fmt"
func test(testArray []int) { for i := 0; i < len(testArray); i++ { testArray[i] += 1 }
} func main() { nums := []int{1, 2, 3} fmt.Printf("nums: %v\n", nums) test(nums) fmt.Printf("nums: %v\n", nums)
}
|
在函数内部修改了切片,函数外部访问修改也会生效。
1 2 3
| $ go run "testSlice.go" nums: [1 2 3] nums: [2 3 4]
|
Map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package main
import "fmt"
func test(testMap map[int]string) { for k, _ := range testMap { testMap[k] = "change it" }
}
func main() { nums := map[int]string{ 1: "one", 2: "two", } fmt.Printf("nums: %v\n", nums) test(nums) fmt.Printf("nums: %v\n", nums)
}
|
函数内部修改了map,外部访问修改也生效。
1 2 3
| $ go run "testMap.go" nums: map[1:one 2:two] nums: map[1:change it 2:change it]
|
通道
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
| package main
import ( "fmt" "sync" "time" )
var wg sync.WaitGroup
func testChannel(cint chan<- int) { defer wg.Done() for i := 0; i < 10; i++ { cint <- i time.Sleep(time.Second) } close(cint) }
func main() { var cint = make(chan int, 1) wg.Add(1) go testChannel(cint) for i := range cint { fmt.Printf("i: %v\n", i) } wg.Wait() }
|
函数testChannel修改channel,主函数访问修改也生效。
其中wg是一个计数器(同步等待组):
- 主函数在执行协程之前,向计数器传入协程的数量:
wg.Add(1);
- 子函数(协程)在执行完毕以后,执行
wg.Done()来给计数器-1;
- 主函数最后要执行
wg.Wait(),阻塞直到子协程
退出。