用 Linux 来学习 Rust 是非常合适的,因为 Rust 工具链在 Linux 上支持最好,而且很多 Rust 生态(编译器、Cargo、系统编程)天然贴近 Unix/Linux 环境。
下面我按从零开始的思路,给你一套清晰路线。
你可以使用:
推荐发行版:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装完成后:
source "$HOME/.cargo/env"
验证:
rustc --version
cargo --version
rustup component add rust-analyzer
rustup component add clippy
rustup component add rustfmt
cargo new hello_rust
cd hello_rust
目录结构:
hello_rust
├── Cargo.toml
└── src
└── main.rs
cargo run
输出:
Hello, world!
推荐组合:
VS Code 安装:
sudo snap install code
安装 Rust 插件:
Rust 很适合学:
示例:读取 Linux 文件
use std::fs;
fn main() {
let content = fs::read_to_string("/etc/os-release")
.expect("无法读取文件");
println!("{}", content);
}
rustup doc --book
ls、grep)cargo build
gdb target/debug/hello_rust
cargo clippy # 代码质量
cargo fmt # 格式化
cargo test # 单元测试
写一个简化版 cat:
use std::env;
use std::fs;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("用法: {} <文件>", args[0]);
return;
}
let content = fs::read_to_string(&args[1]).unwrap();
print!("{}", content);
}
如果你愿意,我可以:
你更想往哪个方向学?