簡體   English   中英

如何指定不明確的關聯類型的超級特征

[英]how to specify ambiguous associated types of supertraits

簡而言之,我面臨以下問題:我願意從tokio_util::codec抽象編解碼器實現。 為此,我定義了一個具有DecoderEncoder<T>作為超特征的特征。

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 Codec 定義中的Error適用於EncodeDecode的語法是什么? Item呢? 最后,還有其他方法嗎?

您可以將關聯類型更改為泛型參數:

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>>>;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM