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

后端 未结 1 2000
[愿得一人]
[愿得一人] 2020-12-20 14:06

My code:

fn request_add(request: &mut Request, collection_name: &\'static str) -> Fallible>
where
    T: ser         


        
相关标签:
1条回答
  • 2020-12-20 14:16

    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?
    0 讨论(0)
提交回复
热议问题