跳到主要内容

Rust 101

· 阅读需 5 分钟

Rust 入门

起步

创建文件 main.rs,内容如下:

fn main() {
println!("Hello, world!");
}

编译代码:

$ rustc main.rs

$ ls
main main.rs

运行代码:

$ ./main

# Windows
$ .\main.exe

工具

Cargo

# 创建项目
$ cargo new <project_name>

# 编译项目
$ cargo build

# 编译并运行项目
$ cargo run

# 检查项目
$ cargo check

rustfmt

$ rustfmt main.rs

变量

修改变量:

fn main() {
let mut x = 4;
println!("x = {}", x); // x = 4
x = 5;
println!("x = {}", x); // x = 5
}

重定义变量:

fn main() {
let x = 4;
println!("x = {}", x); // x = 4
let x = 5;
println!("x = {}", x); // x = 5
}

❌ 不能修改变量类型:

fn main() {
let mut x = 4;
println!("x = {}", x); // x = 4
x = "hello"; // expected integer, found `&str`
println!("x = {}", x);
}

✅ 可以重定义变量类型:

fn main() {
let x = 4;
println!("x = {}", x); // x = 4
let x = "hello";
println!("x = {}", x); // x = hello
}

常量:

fn main() {
const INTERVAL: u32 = 1000;
println!("INTERVAL = {}", INTERVAL); // INTERVAL = 1000

const INTERVAL: u32 = 3000; // ❌ 不能重定义常量
}

数据类型

fn main() {
// Scalar Types
let a = 4; // 默认为i32
let b: i8 = 4; // i8, i16, i32, i64, i128
let c: u8 = 4; // u8, u16, u32, u64, u128
// u32: 0 ~ 2^32-1
// i32: -2^16 ~ 2^16-1

let d = 4.0; // 默认为f64
// f32单精度; f64双精度

let e: bool = true; // bool: true, false

let f: char = 'a'; // char 注意这里的单引号

// Compound Types
// Tuple
let g: (i32, f64, u8) = (500, 6.4, 1); // (i32, f64, u8)
let (m, n, o) = g; // 500, 6.4, 1
// g.0

// Array
let h = [1, 2, 3, 4, 5]; // [i32; 5]
let i: [i32; 5] = [1; 5]; // [1, 1, 1, 1, 1]
// h[0]
}

输入和输出

use std::io;

fn main() {
let mut input = String::new();

io::stdin()
.read_line(&mut input)
.expect("Failed to read line");

println!("{}", input);
}

类型转换

fn main() {
let x: u8 = 8; // 0 - 255
let y: i8 = 10; // -128 - 127
let z = x + y; // error

let x = 8.0f32;
let y = 10.0f32;
let z = x / y; // 0.8

let x = 8_000_i64;
let y = 10_i64;
let z = x / y; // 800

let x = 8_000_i64;
let y = 10_i32;
let z = x / (y as i64); // 800

let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");

println!("{}", input);

let int_input: i64 = input.trim().parse().unwrap();
println!("{}", int_input + 2);
}

条件与流程控制

fn main() {
// < > <= >= == !=
// && || !
// if / else if / else

// let cond = 2 < 3.2; // error

let cond = (2 as f64) < 3.2;
if cond {
println!("2 < 3");
} else if (2 as f64) == 3.2 {
println!("2 == 3");
} else {
println!("2 > 3");
}
println!("Hello, world!");
}

表达式和声明

fn main() {
println!("Hello, world!");

let result = add_numbers(1, 2);
println!("The value of result is: {}", result);

let num = {
let x = 1;
x + 1 // 没有分号,这是一个表达式
};
println!("The value of num is: {}", num);
}

fn add_numbers(x: i32, y: i32) -> i32 {
return x + y;
}

参考资料