我的 typeA
可以包含任何 implements trait Trait
,它是可序列化的,尽管实现 trait 的类型Trait
可能不是。在我的情况下,它不可能 - 它是一个私有非对称密钥:
extern crate serde;
#[macro_use]
extern crate serde_derive;
use serde::de::DeserializeOwned;
use serde::Serialize;
trait Trait {
type SerialisableType: Clone + Serialize + DeserializeOwned;
fn inner(&self) -> &Self::SerialisableType;
}
#[derive(Serialize, Deserialize)]
enum A<T: Trait> {
Variant0(B<T>), // *** NOTE: Compiles if this is commented ***
Variant1(T::SerialisableType),
}
#[derive(Serialize, Deserialize)]
struct B<T: Trait> {
inner: T::SerialisableType,
}
// ==============================================
struct NonSerialisable {
serialisable: Serialisable,
}
impl Trait for NonSerialisable {
type SerialisableType = Serialisable;
fn inner(&self) -> &Self::SerialisableType {
&self.serialisable
}
}
#[derive(Clone, Serialize, Deserialize)]
struct Serialisable(Vec<u8>);
#[derive(Serialize, Deserialize)]
enum E {
Variant0(A<NonSerialisable>),
Variant1(B<NonSerialisable>),
}
fn main() {}
这会出错:
error[E0277]: the trait bound `NonSerialisable: serde::Serialize` is not satisfied
--> src/main.rs:43:10
|
43 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^ the trait `serde::Serialize` is not implemented for `NonSerialisable`
|
= note: required because of the requirements on the impl of `serde::Serialize` for `A<NonSerialisable>`
= note: required by `serde::Serializer::serialize_newtype_variant`
error[E0277]: the trait bound `NonSerialisable: serde::Deserialize<'_>` is not satisfied
--> src/main.rs:43:21
|
43 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^ the trait `serde::Deserialize<'_>` is not implemented for `NonSerialisable`
|
= note: required because of the requirements on the impl of `serde::Deserialize<'_>` for `A<NonSerialisable>`
= note: required by `serde::de::VariantAccess::newtype_variant`
如果我注释掉A::Variant0
,如代码中的内联注释中所述,那么它编译得很好。这使我认为编译器无法推断出B<T>
可序列化的,但实际上它能够推断出,因为它可以确定E
是可序列化的,这也需要B
可序列化。
问题出在哪里?