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 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题