常见编程概念
变量
| let apples = 5; // 不可变
let mut bananas = 5; // 可变
|
输入
| use std::io;
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {}", guess);
|
枚举与强制转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = guess.trim().parse() // 强制转换, 转换类型有定义处决定
.expect("Please type a number!"); // 异常检查
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) { // 比较: match func() { case1 => do1, case2, do2 } ,
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
|
条件
if
| let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
|
三目运算
| let condition = true;
let number = if condition {
5
} else {
6
};
println!("The value of number is: {}", number);
|
Match(switch)
| // 比较: match expression { case1 => do1, case2, do2 }
let guess: u32 = match guess.trim().parse() {
Ok(num) => num, // 将ok中转换的结果返回, 否则继续
Err(_) => continue,
};
|
循环
loop
| label: loop{
break;
continue;
}
|
while
| while number != 0 {
println!("{}!", number);
number = number - 1;
}
|
for
| for number in (1..4).rev() {
println!("{}!", number);
}
|
常量
常量 const, 不能通过变量赋值, 只能由常量表达式计算得到
| const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
|
隐藏变量
| fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("The value of x in the inner scope is: {}", x); // x=12
}
println!("The value of x is: {}", x); // x=6
|
数据类型
基本
- int: i8,i16,i32,i64,i128, u8,u16,..u128 (可以 100_000)
- float: f32, f64
- char
元组
| let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {}", y);
println!("The value of y is: {}", tup.1);
|
数组
| let a: [i32; 5] = [1, 2, 3, 4, 5];
let a = [1..5]; // a=[1,2,3,4,5]
let a = [3; 5]; // a=[5,5,5,5,5]
a[1]; // 存在上下界检查
|
字符串
- str: 不可变序列, string slice, 通常用&str用, 用 String.to_str()或者String[..]转;
- String: 对象, 用 String::from(str) 转;
| let a="Aaa"; // 栈上内存
let b=String::from("hello"); // 堆上内存
s.push_str(", world");
|
Function
| fn print_labeled_measurement(value: i32, unit_label: char) -> value {
println!("The measurement is: {}{}", value, unit_label);
return value;
}
|
代码块与表达式
| let y = {
let x = 3;
x + 1 //注意这里没有分号, 有分号为语句, 无分号是表达式
}; // y=4
|