英文:
Any repercussions from declaring a pointer to a channel in golang?
问题
type Stuff {
ch chan int
}
与
type Stuff {
ch *chan int
}
我知道通道是引用类型,因此在函数返回或作为参数传递时是可变的。在现实世界的程序中,什么时候通道的地址有用?
英文:
type Stuff {
ch chan int
}
versus
type Stuff {
ch *chan int
}
I know that channels are reference types & thus is mutable when returned by functions or as arguments. When is an address of a channel useful in a real world program ?
答案1
得分: 1
也许你的代码中使用了通道来进行日志轮转,并且你想要交换(旋转)日志;交换通道(日志)的指针而不是值。
例如,
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
英文:
Perhaps your channel is used for rotating logs and you want to rotate (swap) logs; swap channel (log) pointers not values.
For example,
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)
}
}
Output:
swapped
y x
not swapped
x y
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论