Appearance
变量5:exercises/variables/variables5.rs
题目
rust
// variables5.rs
//
// Execute `rustlings hint variables5` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn main() {
let number = "T-H-R-E-E"; // don't change this line
println!("Spell a Number : {}", number);
number = 3; // don't rename this variable
println!("Number plus two is : {}", number + 2);
}
题目解析
编译器错误信息如下:
txt
⚠️ Compiling of exercises/variables/variables5.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
--> exercises/variables/variables5.rs:11:14
|
9 | let number = "T-H-R-E-E"; // don't change this line
| ----------- expected due to this value
10 | println!("Spell a Number : {}", number);
11 | number = 3; // don't rename this variable
| ^ expected `&str`, found integer
error[E0369]: cannot add `{integer}` to `&str`
--> exercises/variables/variables5.rs:12:48
|
12 | println!("Number plus two is : {}", number + 2);
| ------ ^ - {integer}
| |
| &str
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0308, E0369.
For more information about an error, try `rustc --explain E0308`.
由于我们定义number
时变量类型为&str
,但是后面我们又使用number = 3;
要将其改为i32类型,由于类型不匹配,编译器报错。
此处,我们想要为现有的变量分配不同的类型的值,并且想重用现有的变量名称,那么我们其实可以借助Rust的变量遮蔽特性。
rust
fn main() {
let number = "T-H-R-E-E"; // don't change this line
println!("Spell a Number : {}", number);
number = 3; // don't rename this variable
let number = 3; // don't rename this variable
println!("Number plus two is : {}", number + 2);
}
笔记
可以定义一个与之前变量同名的新变量。Rustacean 们称之为第一个变量被第二个 隐藏(Shadowing) 了,这意味着当您使用变量的名称时,编译器将看到第二个变量。实际上,第二个变量“遮蔽”了第一个变量,此时任何使用该变量名的行为中都会视为是在使用第二个变量,直到第二个变量自己也被隐藏或第二个变量的作用域结束。可以用相同变量名称来隐藏一个变量,以及重复使用 let 关键字来多次隐藏