Any repercussions from declaring a pointer to a channel in golang?

huangapple go评论139阅读模式
英文:

Any repercussions from declaring a pointer to a channel in golang?

问题

type Stuff {
ch chan int
}

type Stuff {
ch *chan int
}

我知道通道是引用类型,因此在函数返回或作为参数传递时是可变的。在现实世界的程序中,什么时候通道的地址有用?

英文:
  1. type Stuff {
  2. ch chan int
  3. }

versus

  1. type Stuff {
  2. ch *chan int
  3. }

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

也许你的代码中使用了通道来进行日志轮转,并且你想要交换(旋转)日志;交换通道(日志)的指针而不是值。

例如,

  1. package main
  2. import "fmt"
  3. func swapPtr(a, b *chan string) {
  4. *a, *b = *b, *a
  5. }
  6. func swapVal(a, b chan string) {
  7. a, b = b, a
  8. }
  9. func main() {
  10. {
  11. a, b := make(chan string, 1), make(chan string, 1)
  12. a <- "x"
  13. b <- "y"
  14. swapPtr(&a, &b)
  15. fmt.Println("swapped")
  16. fmt.Println(<-a, <-b)
  17. }
  18. {
  19. a, b := make(chan string, 1), make(chan string, 1)
  20. a <- "x"
  21. b <- "y"
  22. swapVal(a, b)
  23. fmt.Println("not swapped")
  24. fmt.Println(<-a, <-b)
  25. }
  26. }

输出结果:

  1. swapped
  2. y x
  3. not swapped
  4. 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,

  1. package main
  2. import &quot;fmt&quot;
  3. func swapPtr(a, b *chan string) {
  4. *a, *b = *b, *a
  5. }
  6. func swapVal(a, b chan string) {
  7. a, b = b, a
  8. }
  9. func main() {
  10. {
  11. a, b := make(chan string, 1), make(chan string, 1)
  12. a &lt;- &quot;x&quot;
  13. b &lt;- &quot;y&quot;
  14. swapPtr(&amp;a, &amp;b)
  15. fmt.Println(&quot;swapped&quot;)
  16. fmt.Println(&lt;-a, &lt;-b)
  17. }
  18. {
  19. a, b := make(chan string, 1), make(chan string, 1)
  20. a &lt;- &quot;x&quot;
  21. b &lt;- &quot;y&quot;
  22. swapVal(a, b)
  23. fmt.Println(&quot;not swapped&quot;)
  24. fmt.Println(&lt;-a, &lt;-b)
  25. }
  26. }

Output:

  1. swapped
  2. y x
  3. not swapped
  4. x y

huangapple
  • 本文由 发表于 2014年4月6日 03:31:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/22885749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定