rust 如何指定超特性的模糊关联类型

bn31dyow  于 2023-01-21  发布在  其他
关注(0)|答案(1)|浏览(148)

简而言之,我面临以下问题:我愿意从tokio_util::codec中抽象出编解码器实现,为此,我定义了一个trait,它将DecoderEncoder<T>作为超trait。

use tokio_util::codec::{Decoder, Encoder};

struct CodecA {}

impl Decoder for CodecA {
    type Item = Vec<u8>;
    type Error = std::io::Error;
...
}

impl Encoder<Vec<u8>> for CodecA {
    type Error = std::io::Error;
...
}

// the synthetic trait based upon Decoder and Encoder
trait Codec<T>: Decoder<> + Encoder<T>  {}

impl Codec<Vec<u8>> for CodecA { }

在后面的代码中,当提供dyn Codec<>作为第二个参数时,我尝试示例化Framed示例。

let stream = ... ;
    let mut lines: Framed<Box<dyn AsyncReadAndWrite>, dyn Codec<Vec<u8>, Error=std::io::Error, Item=Vec<u8>>> ;

    match protocol {
        KindA => lines = Framed::new(stream, CodecA {}),
        KindB => lines = Framed::new(stream, CodecB {}),
    }

这就是我不能满足编译器的地方:

Error[E0222]: ambiguous associated type `Error` in bounds of `codec::Codec<Vec<u8>>`
   --> src/workers.rs:190:74
    |
190 |     let mut lines: Framed<Box<dyn AsyncReadAndWrite>, dyn Codec<Vec<u8>, Error=std::io::Error, Item=Vec<u8>>> ;
    |                                                                          ^^^^^^^^^^^^^^^^^^^^ ambiguous associated type `Error`
    |
    = note: associated type `codec::Codec<Vec<u8>>` could derive from `Encoder<Vec<u8>>`
    = note: associated type `codec::Codec<Vec<u8>>` could derive from `Decoder`

告诉rustc编解码器定义中的Error同时适用于EncodeDecode的语法是什么?Item又如何?最后,是否有其他方法?

3htmauhk

3htmauhk1#

可以将关联类型更改为通用参数:

trait Codec<T, DecoderError, EncoderError>:
    Decoder<Error = DecoderError> + Encoder<T, Error = EncoderError>
{
}

impl<U, T: ?Sized + Decoder + Encoder<U>> Codec<U, <T as Decoder>::Error, <T as Encoder<U>>::Error>
    for T
{
}

let mut lines: Framed<Box<dyn AsyncReadAndWrite>, dyn Codec<Vec<u8>, std::io::Error, std::io::Error, Item = Vec<u8>>>;

相关问题