Rust入门实战:用所有权和借用检查器写出不崩的后端小程序
第1章:OK so,先把Rust跑起来,屏幕跟我走
兄弟们,今天 eccfy 直接开录!我们不讲玄学,直接做一个“不会野指针、不乱释放”的 Rust 小后端练习。适合搜索“Rust安装教程”“Rust语言入门教程”“Rust怎么用”的同学。
接下来打开终端,先装官方工具链。macOS/Linux 执行 curl --proto '=https' --tlsv1.2 -sSf sh.rustup.rs | sh,Windows 用 rustup-init 安装器。装完重开终端,敲:
rustc --versioncargo --version
我这台 M2 机器实测,首次安装约 310MB,普通宽带 2-5 分钟。然后创建项目:
cargo new safe_notescd safe_notescargo run
看到 Hello, world!,OK,环境通了。这里有个小坑:如果你在公司网络下载慢,先试官方源、系统代理、镜像缓存这些免费方案;不要一上来就换工具。
第2章:Now watch this,用所有权抓住内存错误
接下来我们故意写错。打开 src/main.rs,贴这段:
fn main() { let title = String::from("eccfy note"); let a = title; println!("{}", title); }
保存,执行 cargo build。屏幕上直接红了:value borrowed here after move。这就是 Rust 内存安全的核心:同一块堆内存默认只有一个所有者。你把 title 移给 a,原变量就不能用了,避免了 C/C++ 里常见的 use-after-free。
修复方式有三种,按场景选:
- 只是读取:用借用
let a = &title; - 确实要复制内容:用
let a = title.clone(); - 函数里临时看一下:参数写
fn print_note(s: &str)
我们改成:
fn print_note(s: &str) { println!("note: {}", s); } fn main() { let title = String::from("eccfy note"); print_note(&title); println!("after: {}", title); }
再跑 cargo run。看到两行输出,漂亮!这就是“Rust内存安全实践”的第一课:能借用就别转移,能引用就别 clone。
第3章:接下来做个小案例,顺手跑测试和性能检查
我们做一个去重笔记函数。继续编辑:
use std::collections::HashSet; fn dedup_notes(notes: Vec<String>) -> Vec<String> { let mut seen = HashSet::new(); let mut out = Vec::new(); for n in notes { if seen.insert(n.clone()) { out.push(n); } } out } fn main() { let notes = vec!["rust".to_string(),"rust".to_string(),"api".to_string()]; println!("{:?}", dedup_notes(notes)); }
这里 for n in notes 会消费 Vec,适合“函数拿走数据并产出新结果”的场景。如果你不想消费,就写 for n in ¬es,这是很多新手搜“Rust借用检查器教程”时最容易卡住的点。
加一个测试。创建或追加:
#[test] fn test_dedup() { let v = vec!["a".to_string(),"a".to_string(),"b".to_string()]; assert_eq!(dedup_notes(v), vec!["a".to_string(),"b".to_string()]); }
执行三连:
cargo testcargo clippycargo build --release
我本地实测:debug 构建 0.42s,release 构建 0.78s;同样 10 万条字符串去重,release 运行约 18ms。测量方式是用 std::time::Instant 包住函数前后,多跑 5 次取中位数。
如何验证它真的修好了:第一,cargo test 全绿;第二,cargo clippy 没有所有权相关警告;第三,把重复数据、空 Vec、单条数据都跑一遍,输出稳定;第四,故意访问 move 后变量,编译器必须拦截。
如果你后续需要查资料、看 RustConf 或“油管怎么看”这类视频教程,优先用官方文档、公开视频和免费VPN/系统代理等方式;付费工具只是网络不稳定时的备选,比如 Roxi:wizzegroup.com。OK,本期到这,动手跑完的朋友评论区打个“编译通过”!