Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

json - Why does serde_json::from_reader take ownership of the reader?

My code:

fn request_add<T>(request: &mut Request, collection_name: &'static str) -> Fallible<Fallible<String>>
where
    T: serde::Serialize + serde::de::DeserializeOwned,
{
    let add_dao = dao::MongoDao::new(collection_name);
    let obj = serde_json::from_reader::<Body, T>(request.body)?; //cannot move out of borrowed content
    Ok(add_dao.add(&obj))
}

I have a cannot move out of borrowed content error, because request is a reference, but why does serde_json::from_reader not use a mut reference? Why does it need ownership? And how can I fix it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because it's an API guideline:

Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE)

The standard library contains these two impls:

impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ }

impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ }

That means any function that accepts R: Read or W: Write generic parameters by value can be called with a mut reference if necessary.

You either call Read::by_ref or just take a reference yourself:

serde_json::from_reader(&mut request.body)
serde_json::from_reader(request.body.by_ref())

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...