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

帅比萌擦擦* 提交于 2019-12-09 03:32:29

问题


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?


回答1:


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:

  • Read an arbitrary number of bytes from type implementing Read
  • How to use a file with a BufReader and still be able to write to it?
  • Why does Iterator::take_while take ownership of the iterator?


来源:https://stackoverflow.com/questions/51809603/why-does-serde-jsonfrom-reader-take-ownership-of-the-reader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!