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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line