常见概念
//常量
const MAX: u32 = 100_000;
fn main() {
//不可变
let x = 5;
//可变
let mut v = 6;
v = 7
}
隐藏(Shadowing)
可以作为变量名服用
fn main() {
let x = 5;
let x = x + 1;
let x = x + 2;
println!("{}", x);
}
数据类型
fn main() {
let guess: u32 = "42".parse();
let foo = 98_222;
// 四字节Unicode
let c = 'z';
// 元组与解构
let tup = (6.4, 1, 't');
let (x, y, z) = tup;
let a = [1, 2, 4];
}
函数
fn main() {
let x = foo();
}
fn foo() -> i32 {
5
}
控制流
fn main() {
let mut x = 5;
let num = if x > 5 {
5
} else {
6
};
println!("{}", num);
let r = loop {
x += 1;
if x == 10 {
break x;
}
};
println!("{}", r);
}
fn main() {
let a = [1, 2, 4];
for x in a.iter() {
println!("{}", x)
}
for x in (1..4).rev() {
println!("{}", x)
}
}
结构体
元组结构体
struct Color(i32, i32, i32);
结构体方法
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle { width: 3, height: 4};
println!("{}", rect.area());
}