Explanation of into_inner()


I checked the rust documentation on interior mutability. But I find it hard to understand.

interior mutability is when you have an immutable reference (&T) but you can mutate the destination,

I was going through a piece of rust code, and I found the following:

let mut sout = BufWriter::new(stdout());

let mut bout = sout.into_inner()?;


Why do you require sout.into_inner() before calling flush()? sout has already been declared to be mutable.

Raj Mohan


This is not related to interior mutability. into_inner() is simply (by convention) a method that consumes self and returns an inner, “wrapped” object. In this case, the BufWriter wraps the stdout. It moves it into itself in new, so here (as is often the case) into_inner is kind of the reverse of new.

In general, Rust methods are named into_something when they consume self, avoiding clones as much as possible, and to_something when they take &self, potentially cloning some data.


Thank you clearing up my misunderstanding.