dongyu1983 2013-12-11 08:03
浏览 27
已采纳

为什么通道的方向变化不兼容?

I like to program providing interfaces as restrictively as possible, both to avoid bad usage as to be explicit and self-documented.

So, I like to provide directional channels when they are supposed to be used unidirectionally by the user, but of course, internally I have a bidirectional channel copy.

Assigment for the following works:

var internal chan int
var external <-chan int
external = internal

But now I want to provide to the user a <-chan chan<- int type (in the return of a function), but the following won't work:

var internal chan chan int
var external <-chan chan<- int
external = internal // this fails

I have two questions:

  • Exactly why that doesn't work?
  • So, I can declare a variable of <-chan chan<- type, but... can't use such a type in any practical sense? (Because even though there're directional channels, they're AFAIK aways used in orchestration with bidirectional ones, and since assignment is not possible, they can't be used this way)
  • 写回答

3条回答 默认 最新

  • douao3063 2013-12-11 11:53
    关注

    The reason why this does not work

    The specification says this about channel assignability:

    A [channel] value x is assignable to a variable of type T ("x is assignable to T") [when] x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.

    This reflects exactly what you're experiencing:

    • chan (chan int) to <- chan (chan int) works
    • chan (chan int) to <- chan (chan<- int) does not

    The reason for this is that the element types (the ones after the chan keyword) are not equal.

    I can declare it but not use it?

    You can use it but not the way you want to. It is not possible to assign the variables the way you do but by correcting the element types you can indeed use it:

    var internal chan chan<- int
    var external <-chan chan<- int
    external = internal
    

    If you only have your chan chan int type you need to copy your values (Examples on play):

    var internal chan chan int
    var internalCopy chan chan<- int
    
    go func() { for e := range internal { internalCopy <- e } }()
    
    var external <-chan chan<- int
    external = internalCopy
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制