What's the difference between placing "mut" before a variable na

ghz 7months ago ⋅ 66 views

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

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>) { /* ... */ }

Answers

In Rust, the placement of mut in function signatures has different meanings depending on the context.

  1. mut before a parameter name (mut foo) indicates that the binding itself is mutable. This means that the variable foo can be reassigned to refer to a different value within the function.

  2. mut before a type (Box<i32>) indicates that the value being passed is mutable. This means that the data pointed to by the reference (or owned by the Box) can be modified within the function.

In the first function signature fn modify_foo(mut foo: Box<i32>), mut foo indicates that the binding foo is mutable, meaning that you can reassign foo within the function if needed. It doesn't directly affect the mutability of the data inside the Box.

In the second function signature fn modify_foo(foo: &mut i32), &mut i32 indicates that the reference foo is mutable, meaning that the data it refers to (an i32 value) can be modified within the function.

So, the placement of mut in the two function signatures you provided serves different purposes, and they cannot be interchanged directly. The third function signature you suggested fn modify_foo(foo: mut Box<i32>) would not be valid Rust syntax because mut is used before the type, which is not allowed in this context.