rust
Contents
1、变量定义
// 不可变变量
let guess = String::new();
// 不可变变量可以用let 关键字来遮蔽变量
let x = 5;
let x = x + 1;
// 可变变量
let mut guess = String::new();
2、数据类型
// 数值类型
8 位 i8 u8
16 位 i16 u16
32 位 i32 u32
64 位 i64 u64
128 位 i128 u128
arch isize usize
// 浮点
f64 f32
// bool类型
fn main() {
let t = true;
let f: bool = false; // with explicit type annotation
}
// 复合类型
// 元组
let tup: (i32, f64, u8) = (500, 6.4, 1);
// 数组
let a = [1, 2, 3, 4, 5];
// 设置数组类型
let a: [i32; 5] = [1, 2, 3, 4, 5];
3、函数
// 基本函数
fn main() {
println!("Hello, world!");
another_function();
}
fn another_function() {
println!("Another function.");
}
// 带参函数
fn print_labeled_measurement(value: i32, unit_label: char) {
println!("The measurement is: {}{}", value, unit_label);
}
// 带返回值的函数
fn plus_one(x: i32) -> i32 {
x + 1
}
4、流程控制
// if
fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
fn main() {
let number = 3;
if number != 0 {
println!("number was something other than zero");
}
}
// if-else
fn main() {
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 };
// 循环
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {}", result);
}
// while
fn main() {
let mut number = 3;
while number != 0 {
println!("{}!", number);
number -= 1;
}
println!("LIFTOFF!!!");
}
// for
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {}", element);
}
}
5、结构体
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
fn main() {
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
}
fn build_user(email: String, username: String) -> User {
User {
email: email,
username: username,
active: true,
sign_in_count: 1,
}
// 方法
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
}
// match, 类似switch
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => {
println!("Lucky penny!");
1
}
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}