[rust-dev] Mutable files
pcwalton at mozilla.com
Sun Jul 20 18:33:31 PDT 2014
On 7/20/14 6:29 PM, David Henningsson wrote:
> Consider these two examples:
> let mut file = File::open(filename);
> let file = File::open(filename);
> let mut reader = BufferedReader::new(file);
> My question is: in example 2, why doesn't BufferedReader need "file" to
> be mutable? After all, BufferedReader ends up calling file.read(), which
> needs a mutable reference to the file.
> It looks like I'm able to "bypass" the mutability requirement, just
> because I wrap the file inside a BufferedReader?
Because `BufferedReader::new` moves `file` and takes ownership of it.
(You can see this if you try to use `file` again: the compiler will
prevent you.) Mutability is inherited through ownership in Rust: that
is, the current owner determines the mutability of a piece of data. So,
the mutability of `reader` determines the mutability of the `File`
object at the time you try to read, and the mutability restriction is
More information about the Rust-dev