为什么 serde_json::from_reader 取得 reader 的所有权?

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

我的代码:

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))
}

我有一个cannot move out of borrowed content错误,因为request是引用,但为什么serde_json::from_reader不使用mut引用?为什么需要所有权?我该如何解决?

因为它是 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.

您可以致电 Read::by_ref 或自己参考:

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

另请参阅: