[英]cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements for struct made of enums with Serde Deserialize
Why can I auto derive serde::Deserialize
for my WidgetValue
enum, but not for a struct made up entirely of WidgetValue
fields?为什么我可以为我的
WidgetValue
枚举自动派生serde::Deserialize
,但不能为完全由WidgetValue
字段组成的结构?
This seems counterintuitive to me.这对我来说似乎违反直觉。
EDIT: For various reasons, I'm using the WidgetValue enum because I'd like to send different values through a function with the same type signature.编辑:出于各种原因,我使用 WidgetValue 枚举是因为我想通过具有相同类型签名的函数发送不同的值。 See Vector store mixed types of data in Rust , How do I create a heterogeneous collection of objects?
请参阅Vector 在 Rust 中存储混合类型的数据, 如何创建对象的异构集合? , etc.
, 等等。
serde = { version = "1.0.126", features = ["derive"] }
//works fine
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub enum WidgetValue{
Integer32(i32),
Unsized32(u32),
CString(&'static str),
}
//lifetime error
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct DraggableInfo{
parent: WidgetValue,
index: WidgetValue,
draggable_id: WidgetValue,
}
Error:错误:
cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
You can fix the lifetime error, by manually providing a bound on the 'de
lifetime during deserialization.您可以通过在反序列化期间手动提供
'de
生命周期'de
的界限来修复生命周期错误。 Due to the &'static str
the enum WidgetValue
only implements Deserialize<'static>
since no other lifetime works to borrow a &'static str
.由于
&'static str
枚举WidgetValue
仅实现Deserialize<'static>
因为没有其他生命周期可以借用&'static str
。 This leads to an error for DraggableInfo
since by default the 'de
lifetime is not constrained.这会导致
DraggableInfo
出错,因为默认情况下'de
生命周期不受约束。 With this manual bound you declare 'de
to outlive 'static
, making them equal.使用本手册,您可以声明
'de
to outlive 'static
,使它们相等。
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
#[serde(bound(deserialize = "'de: 'static"))]
pub struct DraggableInfo{
parent: WidgetValue,
index: WidgetValue,
draggable_id: WidgetValue,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub enum WidgetValue{
Integer32(i32),
Unsized32(u32),
CString(&'static str),
}
You likely do not want to use it like this though, since you can only derive from 'static
data.不过,您可能不想这样使用它,因为您只能从
'static
数据'static
派生。 You can redefine CString
like this CString(Cow<'static, str>)
to allow both static string literals and deserializing from non-static data.您可以像这样重新定义
CString
CString(Cow<'static, str>)
以允许静态字符串文字和从非静态数据反序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.