Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does io::copy require the reader and writer to both be mutable references?

Tags:

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?

like image 279
Ralph Caraveo Avatar asked Oct 23 '16 03:10

Ralph Caraveo


People also ask

What is a mutable reference in Rust?

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 .

How do you borrow as mutable in Rust?

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.

What are references in Rust?

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.


1 Answers

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.

like image 53
DK. Avatar answered Dec 08 '22 07:12

DK.