Why does std::io::copy
require that both the reader and writer arguments need to be passed as mutable references?
I can understand why the writer needs to be mutated in order to accommodate data being written to it, changing its internal state.
However, why must a reader also be flagged as a mutable reference? If I am only reading data, then wouldn't I just need a reference to a given type and not a mutable reference?
Back to Rust. A mutable reference is a borrow to any type mut T , allowing mutation of T through that reference. The below code illustrates the example of a mutable variable and then mutating its value through a mutable reference ref_i .
First, we change s to be mut . Then we create a mutable reference with &mut s where we call the change function, and update the function signature to accept a mutable reference with some_string: &mut String . This makes it very clear that the change function will mutate the value it borrows.
A reference represents a borrow of some owned value. You can get one by using the & or &mut operators on a value, or by using a ref or ref mut pattern.
Because Read
types are, in general, one-shot: by reading from it, you are mutating it.
Consider standard input: you can only read from that once, so something must be changing. When you read from a socket, you're almost certainly mutating an internal buffer used to account for the differences between the network packets you get, and how much data you want to read at any given moment. How about reading from a Chain
, which is used to concatenate readable things together; without mutation, it can't keep track of which one it's supposed to be reading from.
Sure, it's possible to have a Read
type that doesn't need mutable access to perform a read, but that's not universally true, and because it's not universally true, the Read
trait demands mutable access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With