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

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

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 &quot;fmt&quot;

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 &lt;- &quot;x&quot;
		b &lt;- &quot;y&quot;
		swapPtr(&amp;a, &amp;b)
		fmt.Println(&quot;swapped&quot;)
		fmt.Println(&lt;-a, &lt;-b)
	}
	{
		a, b := make(chan string, 1), make(chan string, 1)
		a &lt;- &quot;x&quot;
		b &lt;- &quot;y&quot;
		swapVal(a, b)
		fmt.Println(&quot;not swapped&quot;)
		fmt.Println(&lt;-a, &lt;-b)
	}
}

Output:

swapped
y x
not swapped
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:

确定