Rust标准库:全面概述

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Rust标准库:全面概述



Rust标准库(std)是语言生态系统的核心,为开发者提供强大且安全的工具,用于创建高性能应用程序。与许多其他语言不同,Rust特别关注内存安全性和零成本抽象,这使得std不仅仅是一组实用工具,更是编写可靠代码的基础。本文将详细解析标准库的主要模块、它们的功能,并提供实际示例。



标准库的主要模块



Rust标准库包含众多模块,几乎涵盖了开发的各个方面。我们来看一下其中的关键模块:



  • std::collections — 数据结构(HashMap, Vec, BTreeMap, HashSet等)
  • std::io — 输入输出(文件读写、控制台操作)
  • std::fs — 文件系统操作
  • std::thread — 多线程
  • std::sync — 线程同步(Mutex, Arc, Barrier)
  • std::net — 网络编程(TCP, UDP)
  • std::path — 文件系统路径操作
  • std::error — 错误处理


使用集合(std::collections)



std::collections模块提供了高效的数据结构。最流行的是Vec<T>(动态数组)。此外,HashMap<K, V>常用于存储键值对,HashSet<T>用于存储唯一元素。



use std::collections::HashMap;

fn main() { let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50);

// 按键访问 match scores.get(&"Blue".to_string()) { Some(score) => println!("Score: {}", score), None => println!("No score found"), }}


输入输出与文件操作(std::io 和 std::fs)



std::io和std::fs模块允许读写文件、处理控制台输入输出。Rust通过所有权系统确保文件操作的安全性。



use std::fs::File;use std::io::{BufRead, BufReader, Write};

fn main() -> std::io::Result<()> { // 写入文件 let mut file = File::create("example.txt")?; file.write_all(b"Hello, Rust!")?;

// 逐行读取文件 let file = File::open("example.txt")?; let reader = BufReader::new(file); for line in reader.lines() { println!("{}", line?); } Ok(())}


多线程(std::thread)



Rust通过std::thread模块提供了安全的多线程模型。编译器借助所有权和借用规则,在编译阶段防止数据竞争。



use std::thread;use std::time::Duration;

fn main() { let handle = thread::spawn(|| { for i in 1..5 { println!("线程: {}", i); thread::sleep(Duration::from_millis(100)); } });

for i in 1..3 { println!("主线程: {}", i); thread::sleep(Duration::from_millis(50)); }

handle.join().unwrap();}


同步(std::sync)



为了在线程间安全地共享数据,可以使用std::sync中的原语:Mutex(互斥锁)、Arc(原子引用计数)和Barrier(同步屏障)。



use std::sync::{Arc, Mutex};use std::thread;

fn main() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![];

for _ in 0..10 {\

推荐