英文:
some questions about channel in go
问题
1-什么条件会导致chan中断?
deliveries <-chan amqp.Delivery
for d := range deliveries {
..
}
如果在chan deliveries中没有更多数据几分钟后,它将中断。
上面的代码与下面的代码相同吗?
deliveries <- chan amqp.Delivery
for {
d, ok := <-deliveries
if !ok {
break
}
//code
}
2-为什么chan不仅返回数据还返回状态?"ok"是什么意思?
3-chan是如何实现的?"ok"是关于客户端的状态,为什么它可以返回"ok"?
英文:
1-what is the condition that make chan break?
deliveries <-chan amqp.Delivery
for d:= range deliveries{
..
}
If there is no more data in chan deliveries about a few minutes,that it will break.
Is the code up is same to below?
deliveries <- chan amqp.Delivery
for{
d,ok:=<-deliveries
if !ok{
break
}
//code
}
2-Why does chan not only return data but also status?And what does the "ok" mean?
3-How does the chan realize?"ok" is the status about client,Why can it return the "ok"?
答案1
得分: 0
-
代码1和代码2不同:第二个代码还会获取
ok
,这表示通道是否被发送方关闭。这使得你的代码更加健壮。 -
通道只能传输一种类型的消息。如果你需要状态码,你需要将它放在消息内部。
英文:
-
Code 1 and 2 differ: The second also fetches
ok
which indicates whether the channel was closed by the sender. This makes your code more robust. -
Channels can only transfer one type of message. If you need status code you ahve to put it inside the message.
答案2
得分: 0
我将先回答问题2和问题3,因为答案会为我对问题1的回答提供背景。
2、3)内置函数close(c)记录不会再向通道c发送更多的值。
在接收表达式中,第二个结果是一个布尔值,指示操作是否成功。如果接收到一个发送的值,则第二个结果为true;如果接收到零值,因为通道已关闭,则为false。
1)通过通道进行范围遍历,接收发送到通道的值,直到通道关闭。
以下循环非常相似。它们都在通道关闭之前接收值。
for v := range c {
// 代码
}
for {
v, ok := <-c
if != ok {
break
}
// 代码
}
这些循环之间的主要区别是变量v
的作用域。在第一个循环之外,v
的作用域是内部的。如果在循环中使用闭包和goroutine,这种区别是重要的。
英文:
I will answer question 2 and 3 first because the answer provides context for my answer to question 1.
2, 3) The builtin function close(c) records that no more values will be sent to the channel c.
The second result in a receive expression is a bool indicating if the operation was successful. The second result is true if a sent value was received or false if the zero value was received because the channel was closed.
- Range over a channel receives values sent on the channel until the channel is closed.
The following loops are very similar. They both receive values until the channel is closed.
for v := range c {
// code
}
for {
v, ok := <-c
if != ok {
break
}
// code
}
The main difference between these loops is the scope of of the variable v
. The scope of v
is outside of the first loop and inside the second loop. This distinction is important if you use a closure and goroutine in the loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论