[英]how to specify ambiguous associated types of supertraits
簡而言之,我面臨以下問題:我願意從tokio_util::codec
抽象編解碼器實現。 為此,我定義了一個具有Decoder
和Encoder<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
適用於Encode
和Decode
的語法是什么? 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.