dpyln64620 2016-04-22 16:06
浏览 16
已采纳

在Go中创建单向频道有什么意义

In Go one can create one-way channels. It's a very convenient feature in case of one want to restrict a set of operations available on the given channel. However, as far as I can see, this feature is useful only for function's arguments and variable's type specification, while creating one-way channels via make looks strange for me. I've read this question, but it's not about creating read (or write)-only channels in Go, it's about usage in general. So, my question is about use cases of the next code:

writeOnly := make(chan<- string)
readOnly := make(<-chan string)
  • 写回答

2条回答 默认 最新

  • doulongsha5478 2016-04-22 16:42
    关注

    Theoretically you can use write only channels for unit testing to ensure for example that your code is not writing more than specific number of times to a channel.

    Something like this: http://play.golang.org/p/_TPtvBa1OQ

    package main
    
    import (
        "fmt"
    )
    
    func MyCode(someChannel chan<- string) {
        someChannel <- "test1"
        fmt.Println("1")
        someChannel <- "test2"
        fmt.Println("2")
        someChannel <- "test3"
        fmt.Println("3")
    }
    
    func main() {
        writeOnly := make(chan<- string, 2) // Make sure the code is writing to channel jsut 2 times
        MyCode(writeOnly)
    }
    

    But that would be pretty silly technique for unit testing. You're better to create a buffered channel and check its contents.

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

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100