简体   繁体   English

Rust:如何为具有泛型类型的结构派生反序列化?

[英]Rust: how to derive Deserialize for struct with generic types?

#[derive(Deserialize)]
struct S<'d, T>
  where T: Deserialize<'d>
{
  foo: T,
  other_field: String
}

The above code fails to compile, complaining unused lifetime parameter, but if I remove it, Deserialize would missing lifetime.上面的代码编译失败,抱怨未使用的生命周期参数,但如果我删除它, Deserialize会丢失生命周期。

Can the above code be made correct without using phantom marker or DeserializeOwned ?可以在不使用幻像标记或DeserializeOwned的情况下使上述代码正确吗?

The code works if you remove the where clause completely.如果您完全删除where子句,该代码将起作用。 The derive will add a T: Deserialize<'de> bound automatically for the derived Deserialize<'de> implementation.派生将为派生的Deserialize<'de>实现自动添加一个T: Deserialize<'de>绑定。

#[derive(Deserialize)]
struct S<T> {
  foo: T,
  other_field: String
}

For Rust it is common to not restrict generic types at struct/enum declarations.对于 Rust,通常不在结构/枚举声明中限制泛型类型。 The generic type is only restricted for impl blocks where the behavior is needed.泛型类型仅对需要行为的impl块进行限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM