Declare-variables
let mut guess = String::new();
let apples = 5;
let apples = 5; // immutable
let mut bananas = 5; // mutable
Rustaceans say that the first variable is shadowed by the second, which means that the second variable is what the compiler will see when you use the name of the variable两个相同变量名的场景,第一个变量会被第二个变量遮蔽,意味着编译器看到的变量值是第二个(相同变量名)变量的值.
fn main() {
let x = 5;
let x = x + 1; // 6
{
let x = x * 2;
println!("The value of x in the inner scope is: {x}"); // 12
}
println!("The value of x is: {x}"); // 6
}
常量constants 可以视为immutable(不可变)的变量,first,你不能对常量使用mut,因为它是默认带有mut的variable变量;second,声明常量的关键字是const而不是let,并且常量的类型必须被注释。
声明常量的示例:
// const 变量名: 类型 = 变量值;
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3; // Rust支持在runtime计算表达式的结果作为常量值
示例代码参考
fn main() {
let x = 5;
println!("The value of x is {x}");
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
println!("The value of THREE_HOURS_IN_SECONDS is {THREE_HOURS_IN_SECONDS}");
const TWELVE: u32 = 12;
println!("The value of TWELVE is {TWELVE}");
let spaces = " ";
println!("The spaces is {spaces}");
let spaces = spaces.len();
println!("The spaces is {spaces}");
}