Rust 入门教程——从零开始的系统编程
作者: CaoZH日期: 2026-01-15本文为原创教程
Rust 连续多年在 Stack Overflow 开发者调查中被评为”最受喜爱的编程语言”。它的内存安全 和零成本抽象 特性,让它在系统编程、WebAssembly、CLI 工具等领域越来越受欢迎。
一、安装 Rust 1 2 3 4 5 6 7 8 9 10 11 12 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh rustc --version cargo --version rustup update rustup doc
Hello World 1 2 3 fn main () { println! ("Hello, Rust!" ); }
1 2 3 4 5 6 7 8 rustc hello.rs ./hello cargo new hello-world cd hello-worldcargo run
二、基础语法 变量与可变性 1 2 3 4 5 6 7 8 9 10 11 12 13 let x = 5 ;let mut y = 5 ;y = 6 ; const MAX_USERS: u32 = 1000 ;let (a, b) = (1 , "hello" );
数据类型 1 2 3 4 5 6 7 8 9 10 11 12 let age: i32 = 28 ; let price: f64 = 99.9 ; let done: bool = true ; let letter: char = 'A' ; let tup: (i32 , f64 , &str ) = (500 , 6.4 , "hello" );let (x, y, z) = tup;let arr: [i32 ; 3 ] = [1 , 2 , 3 ];let first = arr[0 ];
所有权系统 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 fn main () { let s1 = String ::from("hello" ); let s2 = s1; let s3 = s2.clone(); println! ("{}" , s2); let len = calculate_length(&s3); println! ("{} 的长度是 {}" , s3, len); } fn calculate_length (s: &String ) -> usize { s.len() }
函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 fn add (x: i32 , y: i32 ) -> i32 { x + y } struct Point { x: f64 , y: f64 , } impl Point { fn distance (&self , other: &Point) -> f64 { let dx = self .x - other.x; let dy = self .y - other.y; (dx * dx + dy * dy).sqrt() } }
三、实战:CLI 工具 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 use std::env;use std::fs;use std::process;fn main () { let args: Vec <String > = env::args().collect(); if args.len() < 2 { eprintln!("用法: {} <文件路径>" , args[0 ]); process::exit(1 ); } let file_path = &args[1 ]; match read_file(file_path) { Ok (content) => { let line_count = content.lines().count(); let word_count = content.split_whitespace().count(); let char_count = content.chars().count(); println! ("文件: {}" , file_path); println! ("行数: {}" , line_count); println! ("单词数: {}" , word_count); println! ("字符数: {}" , char_count); } Err (e) => { eprintln!("读取文件失败: {}" , e); process::exit(1 ); } } } fn read_file (path: &str ) -> Result <String , std::io::Error> { fs::read_to_string(path) }
四、错误处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 use std::fs::File;use std::io::{self , Read};fn read_username () -> Result <String , io::Error> { let mut file = File::open("user.txt" )?; let mut content = String ::new(); file.read_to_string(&mut content)?; Ok (content.trim().to_string()) } fn find_user (id: i32 ) -> Option <String > { let users = vec! ["Alice" .to_string(), "Bob" .to_string()]; users.get(id as usize ).cloned() }
五、常用命令 1 2 3 4 5 6 7 8 9 cargo new project_name cargo build cargo build --release cargo run cargo check cargo test cargo doc --open cargo add serde cargo publish
六、总结 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ## 核心概念 - 所有权(Ownership)- 借用(Borrowing)- 生命周期(Lifetime)- 模式匹配(Pattern Matching)- 无惧并发(Fearless Concurrency)## 推荐学习路径 1. ✅ 基础语法 + 所有权2. ✅ 枚举与模式匹配3. ✅ 错误处理4. ✅ 泛型与 trait5. ✅ 生命周期6. ✅ 并发编程7. ✅ unsafe Rust
首发于 CaoZH 的笔记