du248227 2012-11-28 01:15
浏览 189
已采纳

Go中的单向通道有什么意义?

I'm learning Go and so far very impressed with it. I've read all the online docs at golang.org and am halfway through Chrisnall's "The Go Programming Language Phrasebook". I get the concept of channels and think that they will be extremely useful. However, I must have missed something important along the way, as I can't see the point to one-way channels.

If I'm interpreting them correctly, a read-only channel can only be received on and a write-only channel can only be transmitted on, so why have a channel that you can send to and never receive on? Can they be cast from one "direction" to the other? If so, again, what's the point if there's no actual constraint? Are they nothing more than a hint to client code of the channel's purpose?

  • 写回答

3条回答 默认 最新

  • doudou521125 2012-11-28 01:48
    关注

    A read-only channel can be made read-only to whomever receives it, while the sender still has a two-way channel on which they can write. For example:

    func F() <-chan int {
        // Create a regular, two-way channel.
        c := make(chan int)
    
        go func() {
            defer close(c)
    
            // Do stuff
            c <- 123
        }()
    
        // Returning it, implicitely converts it to read-only,
        // as per the function return value.
        return c
    }
    

    Whom ever calls F(), receives a channel on which they can only read. This is mostly useful to catch potential miss-uses of a channel at compile time. Because read/write-only channels are distinct types, the compiler can use its existing type-checking mechanisms to ensure the caller does not try to write stuff into a channel it has no business writing to.

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

报告相同问题?

悬赏问题

  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含