【发布时间】:2014-05-18 02:55:28
【问题描述】:
type Stuff {
ch chan int
}
对
type Stuff {
ch *chan int
}
我知道通道是引用类型,因此在由函数或作为参数返回时是可变的。什么时候频道地址在现实世界的程序中有用?
【问题讨论】:
标签: go
type Stuff {
ch chan int
}
对
type Stuff {
ch *chan int
}
我知道通道是引用类型,因此在由函数或作为参数返回时是可变的。什么时候频道地址在现实世界的程序中有用?
【问题讨论】:
标签: go
也许您的频道用于轮换日志并且您想要轮换(交换)日志;交换通道(日志)指针而不是值。
例如,
package main
import "fmt"
func swapPtr(a, b *chan string) {
*a, *b = *b, *a
}
func swapVal(a, b chan string) {
a, b = b, a
}
func main() {
{
a, b := make(chan string, 1), make(chan string, 1)
a <- "x"
b <- "y"
swapPtr(&a, &b)
fmt.Println("swapped")
fmt.Println(<-a, <-b)
}
{
a, b := make(chan string, 1), make(chan string, 1)
a <- "x"
b <- "y"
swapVal(a, b)
fmt.Println("not swapped")
fmt.Println(<-a, <-b)
}
}
输出:
swapped
y x
not swapped
x y
【讨论】: