some questions about channel in go

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

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 &lt;-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 &lt;- chan amqp.Delivery
for{
    d,ok:=&lt;-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. 代码1和代码2不同:第二个代码还会获取ok,这表示通道是否被发送方关闭。这使得你的代码更加健壮。

  2. 通道只能传输一种类型的消息。如果你需要状态码,你需要将它放在消息内部。

英文:
  1. 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.

  2. 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 := &lt;-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.

  1. 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 := &lt;-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.

huangapple
  • 本文由 发表于 2014年10月10日 17:36:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/26296303.html
匿名

发表评论

匿名网友

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

确定