Why do we have std::io::Write::by_ref?

I was browsing through the docs of Write and Read traits and I noticed that they have by_ref(&mut self) -> &mut Self.
This looks like identity function but I'm sure there must be a reason it is there :smiley:
Could anyone give some examples where this would be useful?

Yes, writer.by_ref() is just an alternative way to write &mut writer. For example:

BufWriter::new(&mut file)

is equivalent to

BufWriter::new(file.by_ref())

There aren't many cases where this is useful for the Write trait. It's more useful for traits like Read and Iterator, which also have their own by_ref methods. In those cases, it allows code like this:

let header_reader = (&mut reader).take(HEADER_SIZE);

let item = (&mut iterator).nth(5);

to be written using "method chain" syntax, which can be more readable in many cases:

let header_reader = reader.by_ref().take(HEADER_SIZE);

let item = iterator.by_ref().nth(5);

Unlike those traits, Write doesn't have any adaptors or methods that consume self, so this is rarely necessary. (All of the standard Write methods already take &mut self.)

1 Like