What's the difference between placing "mut" before a variable name and after the ":"?

Jimmy Lu picture Jimmy Lu · Feb 18, 2015 · Viewed 9.2k times · Source

Here are two function signatures I saw in the Rust documentation:

fn modify_foo(mut foo: Box<i32>) { *foo += 1; *foo }
fn modify_foo(foo: &mut i32) { *foo += 1; *foo }

Why the different placement of mut?

It seems that the first function could also be declared as

fn modify_foo(foo: mut Box<i32>) { /* ... */ }

Answer

anderspitman picture anderspitman · Apr 16, 2015

If you're coming from C/C++, it might also be helpful to think of it basically like this:

// Rust          C/C++
    a: &T     == const T* const a; // can't mutate either
mut a: &T     == const T* a;       // can't mutate what is pointed to
    a: &mut T == T* const a;       // can't mutate pointer
mut a: &mut T == T* a;             // can mutate both

You'll notice that these are inverses of each other. C/C++ take a "blacklist" approach, where if you want something to be immutable you have to say so explicitly, while Rust takes a "whitelist" approach, where if you want something to be mutable you have to say so explicitly.