serde_json::from_str
我想制作一个能够从借来的数据( )或拥有的数据( )反序列化的 Serde 结构serde_json::from_reader
。我已经阅读了理解反序列化器生命周期,并且理解了两个特征界限(<'de, T> where T: Deserialize<'de>
和<T> where T: DeserializeOwned
)之间的区别;我想要的是一个实现两个特征边界的结构,以便可以从任一反序列化函数中使用它。
以下代码(playground)拒绝编译:
use serde_json; // 1.0.56
use serde; // 1.0.114
use std::fs;
use std::io;
use std::borrow::Cow;
#[derive(serde::Deserialize)]
struct Resource<'s> {
// The Cow should allow for either borrowed or owned data
#[serde(borrow)]
pub foo: Cow<'s, str>,
}
fn main() {
{
// Works as expected when referencing a string...
let s = "{\"foo\":\"bar\"}";
let resource: Resource = serde_json::from_str(s).unwrap();
}
{
// ...but refuses to compile when reading from a file
let file = fs::File::open("dummy.json").unwrap();
let reader = io::BufReader::new(file);
let resource: Resource = serde_json::from_reader(reader).unwrap();
}
}
如何使该结构同时使用自有数据和借用数据?有没有办法做类似的事情#[serde(borrow_optional)]
?