放置“mut"和“mut"有什么区别?在变量名之前和“:"之后? [英] What's the difference between placing "mut" before a variable name and after the ":"?
问题描述
这是我在 Rust 文档中看到的两个函数签名:
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 }
为什么 mut
的位置不同?
Why the different placement of mut
?
似乎第一个函数也可以声明为
It seems that the first function could also be declared as
fn modify_foo(foo: mut Box<i32>) { /* ... */ }
推荐答案
mut foo: T
表示你有一个名为 foo
的变量,它是一个 T代码>.您可以更改变量引用的内容:
mut foo: T
means you have a variable called foo
that is a T
. You are allowed to change what the variable refers to:
let mut val1 = 2;
val1 = 3; // OK
let val2 = 2;
val2 = 3; // error: re-assignment of immutable variable
这还允许您修改您拥有的结构的字段:
This also lets you modify fields of a struct that you own:
struct Monster { health: u8 }
let mut orc = Monster { health: 93 };
orc.health -= 54;
let goblin = Monster { health: 28 };
goblin.health += 10; // error: cannot assign to immutable field
foo: &mut T
意味着你有一个引用 (&
) 值的变量,你可以改变 (mut
)code>) 引用值(包括字段,如果是结构体):
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):
let val1 = &mut 2;
*val1 = 3; // OK
let val2 = &2;
*val2 = 3; // error: cannot assign to immutable borrowed content
请注意,&mut
仅对引用有意义 - foo: mut T
不是有效语法.如果有意义,您还可以组合使用两个限定符(let mut a: &mut T
).
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.
这篇关于放置“mut"和“mut"有什么区别?在变量名之前和“:"之后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!