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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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?


cannot move out of borrowed content


request


serde_json::from_reader




1 Answer
1



Because it's an API guideline:


R: Read


W: Write



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.


R: Read


W: Write


mut



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


Read::by_ref


serde_json::from_reader(&mut request.body)


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



See also:






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard