Appearance
变量4:exercises/variables/variables4.rs
题目
rust
// variables4.rs
//
// Execute `rustlings hint variables4` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn main() {
let x = 3;
println!("Number {}", x);
x = 5; // don't change this line
println!("Number {}", x);
}
题目解析
编译器错误信息如下:
txt
⚠️ Compiling of exercises/variables/variables4.rs failed! Please try again. Here's the output:
error[E0384]: cannot assign twice to immutable variable `x`
--> exercises/variables/variables4.rs:11:5
|
9 | let x = 3;
| -
| |
| first assignment to `x`
| help: consider making this binding mutable: `mut x`
10 | println!("Number {}", x);
11 | x = 5; // don't change this line
| ^^^^^ cannot assign twice to immutable variable
error: aborting due to previous error
For more information about this error, try `rustc --explain E0384`.
错误信息提示我们,不能对不可变变量二次赋值。
在Rust中,变量绑定默认是不可变的,这里尝试修改x
的值,是不被允许的。如果我们想要修改变量x
,可以使用mut
将其声明为可变的。
rust
fn main() {
let x = 3;
let mut x = 3;
println!("Number {}", x);
x = 5; // don't change this line
println!("Number {}", x);
}
笔记
- 变量默认是不可改变的(immutable)
- 如果要可变,可以使用
mut