在Go语言中,”channel assignment”是什么意思?

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

in Go, what does channel assgiment mean?

问题

这段代码是一个使用通道(channel)实现的质数筛选算法。在这段代码中,ch=ch1是将ch1的值赋给ch,并且这里是浅拷贝。

在Go语言中,通道是一种用于在不同goroutine之间进行通信和同步的机制。通过将一个通道赋值给另一个通道,实际上是将通道的引用传递给了另一个变量。这意味着chch1引用的是同一个通道,它们指向相同的内存地址。因此,对其中一个通道的操作会影响到另一个通道。

go关键字用于启动一个新的goroutine,即一个并发执行的函数。在这段代码中,go Generate(ch)go Filter(ch, ch1, prime)分别启动了两个goroutine。

希望能帮到你!如果还有其他问题,请随时提问。

英文:

i have this code,

// The prime sieve: Daisy-chain Filter processes.
func main() {
	ch := make(chan int) // Create a new channel.
	go Generate(ch)      // Launch Generate goroutine.
	for i := 0; i < 10; i++ {
		prime := <-ch
		print(prime, "\n")
		ch1 := make(chan int)
		go Filter(ch, ch1, prime)
		ch = ch1
	}
}

I am trying to understand what does channel assignment mean. For example ch=ch1,
what does this do? Deep copy or shallow copy?
what does go guarantee for this?

Thanks

答案1

得分: 11

一个通道是一种引用类型。请参阅"通道是否会隐式地通过引用传递"(引用类型包括切片、映射、通道、指针和函数)。另请参阅"Go语言中的映射指针"。

ch = ch1 只是将 ch1 的引用值复制给 ch

英文:

A channel is a reference type. See "Are channels passed by reference implicitly".
(reference types: slices, maps, channels, pointers, functions)
And see "Go - Pointer to map".

ch = ch1 simply copy the reference value of ch1 to ch.

huangapple
  • 本文由 发表于 2015年1月19日 03:57:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/28014168.html
匿名

发表评论

匿名网友

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

确定