doumen6605 2016-06-14 21:41
浏览 11

反映。选择功能需要为什么? 我认为是因为通道必须是反射值?

Under what cases would reflect.Select be needed?

I have found examples, but the use of Select seems contrived.

Any example where reflect.Select is necessary over normal Select?

  • 写回答

1条回答 默认 最新

  • donglu3087 2016-06-14 23:13
    关注

    There was a write-up recently from the guys at MongoDB. Apparently this code is in production use in their mongodump utility.

    The specific code that uses reflect.Select looks like this (from the article):

    // Run multiplexer until it receives an EOF on the control channel.
    func (mux *Multiplexer) Run() {
        for {
            index, value, recv := reflect.Select(mux.selectCases)
            EOF := !recv
            // note that the control channel is always at index 0
            if index == 0 {
                if EOF {
                    return
                }
                muxInput, _ := value.Interface().(*muxInputSource)
                mux.selectCases = append(mux.selectCases, reflect.SelectCase{
                    Dir:  reflect.SelectRecv,
                    Chan: reflect.ValueOf(muxInput.collection),
                    Send: reflect.Value{},
                })
            } else {
                if EOF {
                    mux.writeEOF()
                    mux.selectCases = append(mux.selectCases[:index], mux.selectCases[index+1:]...)
                } else {
                    document, _ := value.Interface().([]byte)
                    mux.writeDocument(document)[]
                }
            }
        }
    }
    

    The reasons I can think that they use reflect.Select instead of a straight select:

    • The number of goroutines (and therefore the number of channels) is determined at runtime (using the -j flag). In fact, it seems to change dynamically with append. (credit to @cnicutar's comment)
    • The type of the channel is determined at runtime. This allows their muxInput.collection type to be anything it wants. (credit to @JimB's comment)
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路