rust for begginers

📅 2026/8/14 4:01:01
rust for begginers
Rust 初学者指南从安装到核心概念帮你快速上手。一、安装 Rustbash# 官方推荐方式使用 rustup curl --proto https --tlsv1.2 -sSf https://sh.rustup.rs | sh # 验证安装 rustc --version cargo --version二、第一个程序rust// main.rs fn main() { println!(Hello, Rust!); }bash# 编译运行 rustc main.rs ./main # 或用 Cargo推荐 cargo new hello cd hello cargo run三、核心概念Rust 的灵魂1. 变量与可变性rustlet x 5; // 不可变默认 let mut y 10; // 可变 y 20; const MAX: u32 100; // 常量必须标注类型 let z 5 3; // 可以覆盖shadowing let z hello; // 甚至可以改变类型2. 所有权Ownership—— Rust 最核心的机制三条规则每个值都有一个所有者同一时间只能有一个所有者所有者离开作用域值被自动释放rustfn main() { let s1 String::from(hello); // s1 拥有这个字符串 let s2 s1; // 所有权转移给 s2move // println!({}, s1); // ❌ 错误s1 不再有效 let x 5; let y x; // ✅ 可以因为 i32 实现了 Copy trait println!(x {}, y {}, x, y); }3. 借用Borrowing不想转移所有权用引用rustfn main() { let s String::from(hello); let len calculate_length(s); // 不可变借用 println!({} 长度是 {}, s, len); // ✅ s 还能用 change(mut s); // 可变借用 } fn calculate_length(s: String) - usize { s.len() // 不获取所有权只是借用 } fn change(s: mut String) { s.push_str(, world); }借用规则要么一个可变引用要么多个不可变引用引用必须始终有效编译器检查防止悬空指针4. 切片Slicerustlet s String::from(hello world); let hello s[0..5]; // 字符串切片 let world s[6..11]; let arr [1, 2, 3, 4, 5]; let slice arr[1..3]; // [2, 3]四、控制流rustlet number 6; if number % 4 0 { println!(能被4整除); } else if number % 3 0 { println!(能被3整除); } else { println!(都不行); } // if 是表达式可以返回值 let condition true; let x if condition { 5 } else { 6 }; // 循环 loop { // 无限循环 break; } while condition { // while 循环 } for i in 1..4 { // 1, 2, 3推荐 println!({}, i); } let arr [10, 20, 30]; for element in arr.iter() { println!(值: {}, element); }五、函数rustfn main() { let result add(5, 3); println!(结果: {}, result); } // 参数类型必须标注返回类型用 - fn add(a: i32, b: i32) - i32 { a b // 表达式无分号就是返回值 }六、结构体与枚举rust// 结构体 struct User { username: String, email: String, sign_in_count: u64, active: bool, } let user1 User { email: String::from(ab.com), username: String::from(alice), active: true, sign_in_count: 1, }; // 元组结构体 struct Point(i32, i32, i32); // 枚举非常强大 enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } // OptionRust 没有 null let some_number Some(5); let absent_number: Optioni32 None; // Result错误处理 enum ResultT, E { Ok(T), Err(E), }七、模式匹配matchrustenum Coin { Penny, Nickel, Dime, Quarter, } fn value_in_cents(coin: Coin) - u8 { match coin { Coin::Penny { println!(Lucky penny!); 1 } Coin::Nickel 5, Coin::Dime 10, Coin::Quarter 25, } } // if let 简化版 let some_value Some(3); if let Some(3) some_value { println!(三); }八、错误处理rustuse std::fs::File; // Result 类型 let f File::open(hello.txt); match f { Ok(file) file, Err(error) panic!(打开文件失败: {:?}, error), } // 简写? 运算符 fn read_username_from_file() - ResultString, io::Error { let mut f File::open(hello.txt)?; // 失败时直接返回 Err let mut s String::new(); f.read_to_string(mut s)?; Ok(s) } // 更简 fn read_username_from_file() - ResultString, io::Error { fs::read_to_string(hello.txt) } // unwrap() / expect() —— 快速但不安全 let f File::open(hello.txt).unwrap(); let f File::open(hello.txt).expect(无法打开文件);九、集合类型rust// Vector let mut v vec![1, 2, 3]; v.push(4); let third v[2]; // 可能 panic let third v.get(2); // 返回 OptionT // String let mut s String::from(foo); s.push_str(bar); let s2 format!({}-{}, s, baz); // HashMap use std::collections::HashMap; let mut scores HashMap::new(); scores.insert(Blue, 10); scores.entry(Yellow).or_insert(50); // 不存在才插入十、生命周期Lifetimesrust// 告诉编译器返回的引用和参数活得一样久 fn longesta(x: a str, y: a str) - a str { if x.len() y.len() { x } else { y } } // 结构体中的生命周期 struct ImportantExcerpta { part: a str, }十一、常用 Cargo 命令bashcargo new project_name # 创建新项目 cargo build # 编译 cargo build --release # 优化编译生产环境 cargo run # 编译并运行 cargo check # 快速检查不生成可执行文件 cargo test # 运行测试 cargo doc --open # 生成并打开文档 cargo add crate_name # 添加依赖十二、学习路线图plain第1周变量、类型、函数、控制流 第2周所有权、借用、切片重点 第3周结构体、枚举、模式匹配 第4周集合类型、错误处理 第5周生命周期、trait、泛型 第6周闭包、迭代器、智能指针 第7周并发编程 fearless concurrency 第8周unsafe Rust、FFI推荐资源表格资源说明The Rust Book官方教程最权威Rustlings小练习边做边学Rust by Example示例驱动Exercism Rust编程练习Rust 的编译器很严格但报错信息非常友好。拥抱编译器错误它们是在帮你避免运行时 bug