本文介绍了为什么serde_json :: from_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引用?为什么需要所有权?我该如何解决?
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?
推荐答案
因为它是 API指南:
impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ }
impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ }
这意味着任何接受R: Read
或W: Write
泛型的函数 如有必要,可以使用mut
引用调用按值设置的参数.
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
或只是自己参考:
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())
另请参阅:
- 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?
这篇关于为什么serde_json :: from_reader拥有读者的所有权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!