douan8473 2014-09-25 18:40 采纳率: 100%
浏览 23
已采纳

列出缓冲通道中的所有元素

Is there a (non destructive) way to list all the element in a buffered channel?

The only thing I can think about is to cycle all of them, reinserting them at the end. This doesn't seem the smartest approach.

Link to playground

c := make(chan int, 100)
c <- 111
c <- 222
for i:=0;i<2;i++ {
element := <- c
fmt.Println(element)
c <- element
}
fmt.Println(len(c))
  • 写回答

3条回答 默认 最新

  • 普通网友 2014-09-25 18:46
    关注

    This thread from 2011 offered some wrapper around a channel in order to enable a Peek() function, but that was more a workaround than anything else.

    type PeekChanInt struct {
            in <-chan int
            out chan int
    }
    

    The general conclusion was:

    A synchronous channel has no head (it's like a zero-length slice)

    You can't do that because

    • a) it gets put back at the tail of the queue rather than the end and
    • b) a writer may have got there first, so the put may block.

    I have wanted a feature like this in the past. It can make sense when there is only one consumer of the channel (I wanted it to peek at the first mouse event to do hit testing before deciding whether to consume it)

    You can simulate it with a process acting as intermediary, but you'd have to do it for each channel type or lose type safety.

    Remember there is no buffering, so if you peek at a value, you'd have to get the value from the other side, which would be equivalent to reading it - but that's wrong because peeking should have no side effects.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上