ds34222 2017-11-27 12:19
浏览 210
已采纳

不能在返回参数中使用msgs(类型<-chan _)作为类型chan _

Have following code:

func consumeQueue(ch *amqp.Channel, q_Name string) (chan amqp.Delivery) {
    msgs, err := ch.Consume(
        q_Name, // queue
        "",     // consumer
        true,   // auto-ack
        false,  // exclusive
        false,  // no-local
        false,  // no-wait
        nil,    // args
    )
    failOnError(err, "Failed to register a consumer")   
    return msgs
}

It throws following compile time exception:

cannot use msgs (type <-chan amqp.Delivery) as type chan amqp.Delivery in return argument

What is wrong?

  • 写回答

1条回答 默认 最新

  • duanjiao5543 2017-11-27 12:22
    关注

    It's perfectly straightforward. You're trying to return a directional channel (in this case a read-only channel) as a general channel that can be used for both reading and writing.

    There's some basic information about channel directions here

    Tl;Dr

    Any chan t can be used as a directional channel. This increases overal typesafety and makes code easier to understand/use for others:

    func Foo() <-chan struct{} {
    }
    

    This tells me Foo returns a channel I can read from. If it were to return just chan struct{}, I'd have to check the docs to see if I'm expected to push something to that channel, or receive from it.

    A non-directional channel can be made directional, but it's not allowed to convert back to a non-directional channel for obvious reasons. You can check the spec on channel types for even more details, but the essence of it is this simple sentence:

    The optional <- operator specifies the channel direction, send or receive. If no direction is given, the channel is bidirectional. A channel may be constrained only to send or only to receive by conversion or assignment.

    solution

    In your particular case, the solution is simple: change the return type to match the channel you have:

    func consumeQueue(ch *amqp.Channel, q_Name string) (<-chan amqp.Delivery) {
    

    As you've noticed: the compiler shouts at you when you try to convert a directional channel into a bidirectional channel. You'll also get a similar error when you try to convert a read-channel into a write channel (written as chan<- amqp.Delivery). So if you get type error messages from the compiler, just check what types it's mentioning... go's compiler spits out pretty self-explanatory errors IMO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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