24

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ralph Caraveo
  • 10,025
  • 7
  • 40
  • 52

1 Answers1

31

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.

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
DK.
  • 55,277
  • 5
  • 189
  • 162