Explanation of into_inner()


#1

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()?;

bout.flush()?;

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

Thanks,
Raj Mohan


#2

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.


#3

Thank you clearing up my misunderstanding.