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>) { /* ... */ }
4条答案
按热度按时间lymnna711#
If you're coming from C/C++, it might also be helpful to think of it basically like this:
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.
mrfwxfqh2#
mut foo: T
means you have a variable calledfoo
that is aT
. You are allowed to change what the variable refers to:This also lets you modify fields of a struct that you own:
foo: &mut T
means you have a variable that refers to (&
) a value and you are allowed to change (mut
) the referred value (including fields, if it is a struct):Note that
&mut
only makes sense with a reference -foo: mut T
is not valid syntax. You can also combine the two qualifiers (let mut a: &mut T
), when it makes sense.ars1skjm3#
The following natural language translation seems to clear things up for me...
where
{binds mutably}
means the binding can be reassigned{mutable value}
means the value's contents can changeNote:
A reference variable such as
x
, as inlet x = &mut y
, is a separate variable from the target variabley
it is pointing to. In particular,x
has its own location on the stack and mutability permissions. As such, ifx
is immutable, as it is here, then it cannot be reassigned to point to some other variable. That restriction is separate from the ability to mutate the target through it, as in*x = some_value
; the target is a distinct variable with its own mutability permissions. However, ifw
is mutable, as inlet mut w = &mut p
, then it can indeed be reassigned to point to some other similarly typed variable:w = &mut z
.jhdbpxl94#
Mutable Variable of Reference Type
When you have
This means that
x
is variable that refers to an instance ofT
, as if by storing the memory address of theT
instance inx
's value. This reference (i.e. the "memory address") is the subject of mutability in this context:x
can be modified to refer to a different instance ofT
like this:but the referant (i.e. the value of the
T
instance to whichx
refers) cannot be changed viax
:Immutable variable of Mutable Reference type
When you have
This means that
x
is a variable that refers to a mutable instance ofT
. In this case, the referent (i.e. the actual value) is the subject of mutability. It can be modified through the reference like thisbut the reference itself (i.e. the "memory address" in the variable
x
) cannot: