本章概述
泛型和特征是Rust类型系统的核心特性,它们提供了强大的抽象能力和代码复用机制。泛型允许我们编写适用于多种类型的代码,而特征定义了类型必须实现的行为。本章将深入探讨这些概念,帮助你构建灵活且类型安全的代码。
学习目标
- 🎯 理解泛型的概念和用途
- 🎯 掌握泛型函数、结构体和枚举的定义
- 🎯 学会特征的定义和实现
- 🎯 了解特征边界和关联类型
- 🎯 掌握高级特征模式
- 🎯 学会构建通用数据结构
9.1 泛型基础
9.1.1 泛型函数
fn main() {
println!("🔄 泛型函数");
println!("==========");
demonstrate_basic_generics();
demonstrate_multiple_type_parameters();
demonstrate_generic_constraints();
demonstrate_where_clauses();
}
fn demonstrate_basic_generics() {
println!("\n基础泛型函数:");
// 基本泛型函数
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list {
if item > largest {
largest = item;
}
}
largest
}
// 测试不同类型
let numbers = vec![34, 50, 25, 100, 65];
let result = largest(&numbers);
println!("最大数字: {}", result);
let chars = vec!['y', 'm', 'a', 'q'];
let result = largest(&chars);
println!("最大字符: {}", result);
// 泛型交换函数
fn swap<T>(a: &mut T, b: &mut T) {
std::mem::swap(a, b);
}
let mut x = 5;
let mut y = 10;
println!("交换前: x = {}, y = {}", x, y);
swap(&mut x, &mut y);
println!("交换后: x = {}, y = {}", x, y);
let mut s1 = String::from("hello");
let mut s2 = String::from("world");
println!("交换前: s1 = {}, s2 = {}", s1, s2);
swap(&mut s1, &mut s2);
println!("交换后: s1 = {}, s2 = {}", s1, s2);
// 泛型比较函数
fn compare<T: PartialEq>(a: &T, b: &T) -> bool {
a == b
}
println!("5 == 5: {}", compare(&5, &5));
println!("\"hello\" == \"world\": {}", compare(&"hello", &"world"));
// 泛型转换函数
fn convert_to_string<T: std::fmt::Display>(value: T) -> String {
format!("{}", value)
}
println!("数字转字符串: {}", convert_to_string(42));
println!("浮点转字符串: {}", convert_to_string(3.14));
println!("布尔转字符串: {}", convert_to_string(true));
}
fn demonstrate_multiple_type_parameters() {
println!("\n多个类型参数:");
// 多个泛型参数
fn pair<T, U>(first: T, second: U) -> (T, U) {
(first, second)
}
let p1 = pair(42, "hello");
println!("配对1: {:?}", p1);
let p2 = pair(3.14, true);
println!("配对2: {:?}", p2);
// 泛型映射函数
fn map_pair<T, U, V, W, F, G>(pair: (T, U), f: F, g: G) -> (V, W)
where
F: FnOnce(T) -> V,
G: FnOnce(U) -> W,
{
(f(pair.0), g(pair.1))
}
let original = (42, "hello");
let mapped = map_pair(original, |x| x * 2, |s| s.len());
println!("映射结果: {:?}", mapped);
// 泛型合并函数
fn combine<T, U, V, F>(a: T, b: U, combiner: F) -> V
where
F: FnOnce(T, U) -> V,
{
combiner(a, b)
}
let result1 = combine(10, 20, |x, y| x + y);
println!("数字合并: {}", result1);
let result2 = combine("Hello", " World", |s1, s2| format!("{}{}", s1, s2));
println!("字符串合并: {}", result2);
let result3 = combine(vec![1, 2], vec![3, 4], |mut v1, v2| {
v1.extend(v2);
v1
});
println!("向量合并: {:?}", result3);
}
fn demonstrate_generic_constraints() {
println!("\n泛型约束:");
// 使用Debug约束
fn print_debug<T: std::fmt::Debug>(value: T) {
println!("调试输出: {:?}", value);
}
print_debug(42);
print_debug("hello");
print_debug(vec![1, 2, 3]);
// 使用Clone约束
fn duplicate<T: Clone>(value: T) -> (T, T) {
let cloned = value.clone();
(value, cloned)
}
let (original, copy) = duplicate(String::from("hello"));
println!("原始: {}, 复制: {}", original, copy);
// 使用Default约束
fn create_default<T: Default>() -> T {
T::default()
}
let default_int: i32 = create_default();
let default_string: String = create_default();
let default_vec: Vec<i32> = create_default();
println!("默认i32: {}", default_int);
println!("默认String: '{}'", default_string);
println!("默认Vec: {:?}", default_vec);
// 组合约束
fn process<T>(value: T) -> String
where
T: std::fmt::Debug + Clone + Default,
{
let cloned = value.clone();
let default = T::default();
format!("值: {:?}, 克隆: {:?}, 默认: {:?}", value, cloned, default)
}
println!("{}", process(42));
println!("{}", process(String::from("test")));
}
fn demonstrate_where_clauses() {
println!("\nwhere子句:");
// 复杂的where子句
fn complex_function<T, U, V>(t: T, u: U) -> V
where
T: std::fmt::Display + Clone,
U: std::fmt::Debug + Default,
V: From<String>,
{
let t_string = format!("{}", t);
let u_debug = format!("{:?}", u);
let combined = format!("{} - {}", t_string, u_debug);
V::from(combined)
}
let result: String = complex_function(42, vec![1, 2, 3]);
println!("复杂函数结果: {}", result);
// 条件实现
struct Wrapper<T>(T);
impl<T> Wrapper<T>
where
T: std::fmt::Display,
{
fn display(&self) {
println!("包装的值: {}", self.0);
}
}
impl<T> Wrapper<T>
where
T: std::fmt::Debug,
{
fn debug(&self) {
println!("调试包装的值: {:?}", self.0);
}
}
let w1 = Wrapper(42);
w1.display();
w1.debug();
let w2 = Wrapper("hello");
w2.display();
w2.debug();
// 关联类型约束
fn process_iterator<I>(iter: I)
where
I: Iterator,
I::Item: std::fmt::Display,
{
for item in iter {
println!("迭代项: {}", item);
}
}
process_iterator(vec![1, 2, 3].into_iter());
process_iterator(vec!["a", "b", "c"].into_iter());
}
rustc generic_functions.rs && ./generic_functions
9.1.2 泛型结构体和枚举
fn main() {
println!("🏗️ 泛型结构体和枚举");
println!("==================");
demonstrate_generic_structs();
demonstrate_generic_enums();
demonstrate_generic_methods();
demonstrate_associated_functions();
}
fn demonstrate_generic_structs() {
println!("\n泛型结构体:");
// 基本泛型结构体
#[derive(Debug, Clone)]
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn new(x: T, y: T) -> Self {
Point { x, y }
}
}
let integer_point = Point::new(5, 10);
let float_point = Point::new(1.0, 4.0);
println!("整数点: {:?}", integer_point);
println!("浮点点: {:?}", float_point);
// 多个泛型参数的结构体
#[derive(Debug)]
struct Pair<T, U> {
first: T,
second: U,
}
impl<T, U> Pair<T, U> {
fn new(first: T, second: U) -> Self {
Pair { first, second }
}
fn get_first(&self) -> &T {
&self.first
}
fn get_second(&self) -> &U {
&self.second
}
fn swap(self) -> Pair<U, T> {
Pair {
first: self.second,
second: self.first,
}
}
}
let pair = Pair::new("hello", 42);
println!("原始配对: {:?}", pair);
let swapped = pair.swap();
println!("交换后配对: {:?}", swapped);
// 泛型容器
#[derive(Debug)]
struct Container<T> {
items: Vec<T>,
}
impl<T> Container<T> {
fn new() -> Self {
Container { items: Vec::new() }
}
fn add(&mut self, item: T) {
self.items.push(item);
}
fn get(&self, index: usize) -> Option<&T> {
self.items.get(index)
}
fn len(&self) -> usize {
self.items.len()
}
fn is_empty(&self) -> bool {
self.items.is_empty()
}
}
impl<T: Clone> Container<T> {
fn duplicate_all(&self) -> Vec<T> {
self.items.iter().cloned().collect()
}
}
let mut int_container = Container::new();
int_container.add(1);
int_container.add(2);
int_container.add(3);
println!("整数容器: {:?}", int_container);
println!("容器长度: {}", int_container.len());
if let Some(first) = int_container.get(0) {
println!("第一个元素: {}", first);
}
let duplicated = int_container.duplicate_all();
println!("复制的元素: {:?}", duplicated);
// 嵌套泛型
#[derive(Debug)]
struct Matrix<T> {
data: Vec<Vec<T>>,
rows: usize,
cols: usize,
}
impl<T: Clone + Default> Matrix<T> {
fn new(rows: usize, cols: usize) -> Self {
let data = vec![vec![T::default(); cols]; rows];
Matrix { data, rows, cols }
}
fn set(&mut self, row: usize, col: usize, value: T) -> Result<(), String> {
if row >= self.rows || col >= self.cols {
return Err("索引超出范围".to_string());
}
self.data[row][col] = value;
Ok(())
}
fn get(&self, row: usize, col: usize) -> Result<&T, String> {
if row >= self.rows || col >= self.cols {
return Err("索引超出范围".to_string());
}
Ok(&self.data[row][col])
}
}
let mut matrix: Matrix<i32> = Matrix::new(2, 3);
matrix.set(0, 0, 1).unwrap();
matrix.set(0, 1, 2).unwrap();
matrix.set(1, 2, 9).unwrap();
println!("矩阵: {:?}", matrix);
if let Ok(value) = matrix.get(0, 1) {
println!("矩阵[0][1] = {}", value);
}
}
fn demonstrate_generic_enums() {
println!("\n泛型枚举:");
// 自定义Option类型
#[derive(Debug, Clone)]
enum MyOption<T> {
Some(T),
None,
}
impl<T> MyOption<T> {
fn is_some(&self) -> bool {
matches!(self, MyOption::Some(_))
}
fn is_none(&self) -> bool {
matches!(self, MyOption::None)
}
fn unwrap(self) -> T {
match self {
MyOption::Some(value) => value,
MyOption::None => panic!("在None上调用unwrap"),
}
}
fn unwrap_or(self, default: T) -> T {
match self {
MyOption::Some(value) => value,
MyOption::None => default,
}
}
fn map<U, F>(self, f: F) -> MyOption<U>
where
F: FnOnce(T) -> U,
{
match self {
MyOption::Some(value) => MyOption::Some(f(value)),
MyOption::None => MyOption::None,
}
}
}
let some_value = MyOption::Some(42);
let none_value: MyOption<i32> = MyOption::None;
println!("some_value: {:?}", some_value);
println!("none_value: {:?}", none_value);
println!("some_value.is_some(): {}", some_value.is_some());
println!("none_value.is_none(): {}", none_value.is_none());
let mapped = some_value.map(|x| x * 2);
println!("映射后: {:?}", mapped);
// 自定义Result类型
#[derive(Debug)]
enum MyResult<T, E> {
Ok(T),
Err(E),
}
impl<T, E> MyResult<T, E> {
fn is_ok(&self) -> bool {
matches!(self, MyResult::Ok(_))
}
fn is_err(&self) -> bool {
matches!(self, MyResult::Err(_))
}
fn unwrap(self) -> T {
match self {
MyResult::Ok(value) => value,
MyResult::Err(_) => panic!("在Err上调用unwrap"),
}
}
fn unwrap_or(self, default: T) -> T {
match self {
MyResult::Ok(value) => value,
MyResult::Err(_) => default,
}
}
fn map<U, F>(self, f: F) -> MyResult<U, E>
where
F: FnOnce(T) -> U,
{
match self {
MyResult::Ok(value) => MyResult::Ok(f(value)),
MyResult::Err(error) => MyResult::Err(error),
}
}
fn map_err<F, G>(self, f: G) -> MyResult<T, F>
where
G: FnOnce(E) -> F,
{
match self {
MyResult::Ok(value) => MyResult::Ok(value),
MyResult::Err(error) => MyResult::Err(f(error)),
}
}
}
fn divide(a: f64, b: f64) -> MyResult<f64, String> {
if b == 0.0 {
MyResult::Err("除零错误".to_string())
} else {
MyResult::Ok(a / b)
}
}
let result1 = divide(10.0, 2.0);
let result2 = divide(10.0, 0.0);
println!("10.0 / 2.0 = {:?}", result1);
println!("10.0 / 0.0 = {:?}", result2);
let mapped_result = result1.map(|x| x * 2.0);
println!("映射后的结果: {:?}", mapped_result);
// 泛型树结构
#[derive(Debug, Clone)]
enum Tree<T> {
Empty,
Node {
value: T,
left: Box<Tree<T>>,
right: Box<Tree<T>>,
},
}
impl<T> Tree<T> {
fn new() -> Self {
Tree::Empty
}
fn leaf(value: T) -> Self {
Tree::Node {
value,
left: Box::new(Tree::Empty),
right: Box::new(Tree::Empty),
}
}
fn node(value: T, left: Tree<T>, right: Tree<T>) -> Self {
Tree::Node {
value,
left: Box::new(left),
right: Box::new(right),
}
}
fn is_empty(&self) -> bool {
matches!(self, Tree::Empty)
}
}
impl<T: std::fmt::Display> Tree<T> {
fn print_inorder(&self) {
match self {
Tree::Empty => {},
Tree::Node { value, left, right } => {
left.print_inorder();
print!("{} ", value);
right.print_inorder();
}
}
}
}
let tree = Tree::node(
5,
Tree::node(3, Tree::leaf(1), Tree::leaf(4)),
Tree::node(7, Tree::leaf(6), Tree::leaf(9)),
);
println!("\n树结构: {:?}", tree);
print!("中序遍历: ");
tree.print_inorder();
println!();
}
fn demonstrate_generic_methods() {
println!("\n泛型方法:");
struct Converter;
impl Converter {
// 泛型方法
fn convert<T, U>(value: T) -> U
where
U: From<T>,
{
U::from(value)
}
fn try_convert<T, U>(value: T) -> Result<U, <U as TryFrom<T>>::Error>
where
U: TryFrom<T>,
{
U::try_from(value)
}
}
// 测试转换
let int_value = 42;
let float_value: f64 = Converter::convert(int_value);
println!("i32 -> f64: {} -> {}", int_value, float_value);
let string_value: String = Converter::convert("hello");
println!("&str -> String: {}", string_value);
// 尝试转换
let large_value = 300u16;
match Converter::try_convert::<u16, u8>(large_value) {
Ok(converted) => println!("u16 -> u8: {} -> {}", large_value, converted),
Err(error) => println!("转换失败: {:?}", error),
}
// 结构体的泛型方法
struct Processor<T> {
data: T,
}
impl<T> Processor<T> {
fn new(data: T) -> Self {
Processor { data }
}
fn process<U, F>(&self, f: F) -> U
where
F: FnOnce(&T) -> U,
{
f(&self.data)
}
fn transform<U, F>(self, f: F) -> Processor<U>
where
F: FnOnce(T) -> U,
{
Processor::new(f(self.data))
}
}
let processor = Processor::new(vec![1, 2, 3, 4, 5]);
let sum = processor.process(|data| data.iter().sum::<i32>());
println!("向量和: {}", sum);
let string_processor = processor.transform(|data| {
format!("{:?}", data)
});
let length = string_processor.process(|data| data.len());
println!("字符串长度: {}", length);
}
fn demonstrate_associated_functions() {
println!("\n关联函数:");
struct Builder<T> {
items: Vec<T>,
}
impl<T> Builder<T> {
// 关联函数(静态方法)
fn new() -> Self {
Builder { items: Vec::new() }
}
fn with_capacity(capacity: usize) -> Self {
Builder {
items: Vec::with_capacity(capacity),
}
}
fn from_vec(vec: Vec<T>) -> Self {
Builder { items: vec }
}
fn add(mut self, item: T) -> Self {
self.items.push(item);
self
}
fn build(self) -> Vec<T> {
self.items
}
}
// 使用构建器模式
let numbers = Builder::new()
.add(1)
.add(2)
.add(3)
.build();
println!("构建的数字向量: {:?}", numbers);
let strings = Builder::with_capacity(10)
.add("hello")
.add("world")
.build();
println!("构建的字符串向量: {:?}", strings);
let from_existing = Builder::from_vec(vec![10, 20, 30])
.add(40)
.add(50)
.build();
println!("从现有向量构建: {:?}", from_existing);
}
rustc generic_structs_enums.rs && ./generic_structs_enums
9.2 特征基础
9.2.1 特征定义和实现
fn main() {
println!("🎭 特征基础");
println!("==========");
demonstrate_basic_traits();
demonstrate_default_implementations();
demonstrate_trait_bounds();
demonstrate_multiple_traits();
}
fn demonstrate_basic_traits() {
println!("\n基础特征:");
// 定义基本特征
trait Drawable {
fn draw(&self);
fn area(&self) -> f64;
}
// 为结构体实现特征
struct Circle {
radius: f64,
}
impl Drawable for Circle {
fn draw(&self) {
println!("绘制圆形,半径: {}", self.radius);
}
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
struct Rectangle {
width: f64,
height: f64,
}
impl Drawable for Rectangle {
fn draw(&self) {
println!("绘制矩形,宽: {}, 高: {}", self.width, self.height);
}
fn area(&self) -> f64 {
self.width * self.height
}
}
// 使用特征
let circle = Circle { radius: 5.0 };
let rectangle = Rectangle { width: 10.0, height: 6.0 };
circle.draw();
println!("圆形面积: {:.2}", circle.area());
rectangle.draw();
println!("矩形面积: {:.2}", rectangle.area());
// 特征对象
let shapes: Vec<Box<dyn Drawable>> = vec![
Box::new(Circle { radius: 3.0 }),
Box::new(Rectangle { width: 4.0, height: 5.0 }),
Box::new(Circle { radius: 2.5 }),
];
println!("\n绘制所有形状:");
for shape in &shapes {
shape.draw();
println!("面积: {:.2}", shape.area());
}
let total_area: f64 = shapes.iter().map(|shape| shape.area()).sum();
println!("总面积: {:.2}", total_area);
}
fn demonstrate_default_implementations() {
println!("\n默认实现:");
// 带默认实现的特征
trait Describable {
fn name(&self) -> &str;
// 默认实现
fn description(&self) -> String {
format!("这是一个{}", self.name())
}
fn detailed_description(&self) -> String {
format!("详细信息: {}", self.description())
}
}
struct Book {
title: String,
author: String,
}
impl Describable for Book {
fn name(&self) -> &str {
&self.title
}
// 重写默认实现
fn description(&self) -> String {
format!("《{}》由{}著", self.title, self.author)
}
}
struct Movie {
title: String,
director: String,
}
impl Describable for Movie {
fn name(&self) -> &str {
&self.title
}
// 使用默认实现
}
let book = Book {
title: "Rust编程语言".to_string(),
author: "Steve Klabnik".to_string(),
};
let movie = Movie {
title: "黑客帝国".to_string(),
director: "沃卓斯基姐妹".to_string(),
};
println!("书籍名称: {}", book.name());
println!("书籍描述: {}", book.description());
println!("书籍详细描述: {}", book.detailed_description());
println!("\n电影名称: {}", movie.name());
println!("电影描述: {}", movie.description());
println!("电影详细描述: {}", movie.detailed_description());
// 特征的关联函数
trait Creatable {
fn create() -> Self;
fn create_with_name(name: String) -> Self
where
Self: Sized;
}
#[derive(Debug)]
struct User {
name: String,
id: u32,
}
impl Creatable for User {
fn create() -> Self {
User {
name: "匿名用户".to_string(),
id: 0,
}
}
fn create_with_name(name: String) -> Self {
User {
name,
id: rand::random(),
}
}
}
let anonymous_user = User::create();
let named_user = User::create_with_name("Alice".to_string());
println!("\n匿名用户: {:?}", anonymous_user);
println!("命名用户: {:?}", named_user);
}
fn demonstrate_trait_bounds() {
println!("\n特征边界:");
// 使用特征边界的函数
fn print_info<T: std::fmt::Display + std::fmt::Debug>(item: T) {
println!("Display: {}", item);
println!("Debug: {:?}", item);
}
print_info(42);
print_info("hello");
// 特征边界的where子句
fn compare_and_print<T>(a: T, b: T)
where
T: PartialOrd + std::fmt::Display + Copy,
{
if a > b {
println!("{} 大于 {}", a, b);
} else if a < b {
println!("{} 小于 {}", a, b);
} else {
println!("{} 等于 {}", a, b);
}
}
compare_and_print(10, 5);
compare_and_print(3.14, 2.71);
compare_and_print('a', 'z');
// 返回实现特征的类型
fn create_iterator() -> impl Iterator<Item = i32> {
(0..5).map(|x| x * x)
}
println!("\n平方数:");
for square in create_iterator() {
println!("{}", square);
}
// 条件特征实现
struct Wrapper<T>(T);
impl<T: std::fmt::Display> std::fmt::Display for Wrapper<T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Wrapper({})", self.0)
}
}
let wrapped_int = Wrapper(42);
let wrapped_string = Wrapper("hello");
println!("包装的整数: {}", wrapped_int);
println!("包装的字符串: {}", wrapped_string);
}
fn demonstrate_multiple_traits() {
println!("\n多个特征:");
// 定义多个特征
trait Flyable {
fn fly(&self);
}
trait Swimmable {
fn swim(&self);
}
trait Walkable {
fn walk(&self);
}
// 实现多个特征
struct Duck {
name: String,
}
impl Flyable for Duck {
fn fly(&self) {
println!("{} 在飞翔", self.name);
}
}
impl Swimmable for Duck {
fn swim(&self) {
println!("{} 在游泳", self.name);
}
}
impl Walkable for Duck {
fn walk(&self) {
println!("{} 在走路", self.name);
}
}
struct Fish {
species: String,
}
impl Swimmable for Fish {
fn swim(&self) {
println!("{} 在水中游泳", self.species);
}
}
let duck = Duck {
name: "唐老鸭".to_string(),
};
let fish = Fish {
species: "金鱼".to_string(),
};
duck.fly();
duck.swim();
duck.walk();
fish.swim();
// 需要多个特征的函数
fn demonstrate_versatility<T>(animal: &T)
where
T: Flyable + Swimmable + Walkable,
{
println!("这个动物很全能:");
animal.fly();
animal.swim();
animal.walk();
}
demonstrate_versatility(&duck);
// 特征组合
trait Amphibious: Swimmable + Walkable {
fn transition(&self) {
println!("从水中到陆地");
self.swim();
self.walk();
}
}
struct Frog {
name: String,
}
impl Swimmable for Frog {
fn swim(&self) {
println!("{} 在池塘里游泳", self.name);
}
}
impl Walkable for Frog {
fn walk(&self) {
println!("{} 在陆地上跳跃", self.name);
}
}
impl Amphibious for Frog {}
let frog = Frog {
name: "青蛙王子".to_string(),
};
frog.transition();
}
// 模拟rand::random()函数
mod rand {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::time::{SystemTime, UNIX_EPOCH};
pub fn random<T>() -> T
where
T: From<u32>,
{
let mut hasher = DefaultHasher::new();
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
.hash(&mut hasher);
T::from((hasher.finish() % u32::MAX as u64) as u32)
}
}
rustc traits_basics.rs && ./traits_basics
9.2.2 关联类型和高级特征
fn main() {
println!("🚀 高级特征");
println!("==========");
demonstrate_associated_types();
demonstrate_operator_overloading();
demonstrate_trait_objects();
demonstrate_advanced_patterns();
}
fn demonstrate_associated_types() {
println!("\n关联类型:");
// 使用关联类型的迭代器特征
trait MyIterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
fn collect_all(mut self) -> Vec<Self::Item>
where
Self: Sized,
{
let mut result = Vec::new();
while let Some(item) = self.next() {
result.push(item);
}
result
}
}
// 数字范围迭代器
struct Range {
current: i32,
end: i32,
}
impl Range {
fn new(start: i32, end: i32) -> Self {
Range { current: start, end }
}
}
impl MyIterator for Range {
type Item = i32;
fn next(&mut self) -> Option<Self::Item> {
if self.current < self.end {
let current = self.current;
self.current += 1;
Some(current)
} else {
None
}
}
}
let mut range = Range::new(1, 5);
println!("手动迭代:");
while let Some(value) = range.next() {
println!("{}", value);
}
let range2 = Range::new(10, 15);
let collected = range2.collect_all();
println!("收集的值: {:?}", collected);
// 图的特征
trait Graph {
type Node;
type Edge;
fn add_node(&mut self, node: Self::Node);
fn add_edge(&mut self, from: &Self::Node, to: &Self::Node, edge: Self::Edge);
fn get_neighbors(&self, node: &Self::Node) -> Vec<&Self::Node>;
}
// 简单的字符串图实现
#[derive(Debug)]
struct StringGraph {
nodes: Vec<String>,
edges: Vec<(String, String, String)>, // (from, to, label)
}
impl StringGraph {
fn new() -> Self {
StringGraph {
nodes: Vec::new(),
edges: Vec::new(),
}
}
}
impl Graph for StringGraph {
type Node = String;
type Edge = String;
fn add_node(&mut self, node: Self::Node) {
if !self.nodes.contains(&node) {
self.nodes.push(node);
}
}
fn add_edge(&mut self, from: &Self::Node, to: &Self::Node, edge: Self::Edge) {
self.edges.push((from.clone(), to.clone(), edge));
}
fn get_neighbors(&self, node: &Self::Node) -> Vec<&Self::Node> {
self.edges
.iter()
.filter(|(from, _, _)| from == node)
.map(|(_, to, _)| to)
.collect()
}
}
let mut graph = StringGraph::new();
graph.add_node("A".to_string());
graph.add_node("B".to_string());
graph.add_node("C".to_string());
graph.add_edge(&"A".to_string(), &"B".to_string(), "连接1".to_string());
graph.add_edge(&"A".to_string(), &"C".to_string(), "连接2".to_string());
println!("\n图结构: {:?}", graph);
let neighbors = graph.get_neighbors(&"A".to_string());
println!("A的邻居: {:?}", neighbors);
// 转换特征
trait Convert<T> {
type Output;
type Error;
fn convert(&self, input: T) -> Result<Self::Output, Self::Error>;
}
struct StringToNumber;
impl Convert<String> for StringToNumber {
type Output = i32;
type Error = String;
fn convert(&self, input: String) -> Result<Self::Output, Self::Error> {
input.parse().map_err(|_| format!("无法解析: {}", input))
}
}
impl Convert<&str> for StringToNumber {
type Output = i32;
type Error = String;
fn convert(&self, input: &str) -> Result<Self::Output, Self::Error> {
input.parse().map_err(|_| format!("无法解析: {}", input))
}
}
let converter = StringToNumber;
match converter.convert("42".to_string()) {
Ok(num) => println!("转换成功: {}", num),
Err(err) => println!("转换失败: {}", err),
}
match converter.convert("abc") {
Ok(num) => println!("转换成功: {}", num),
Err(err) => println!("转换失败: {}", err),
}
}
fn demonstrate_operator_overloading() {
println!("\n操作符重载:");
use std::ops::{Add, Sub, Mul, Div};
// 自定义向量类型
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vector2D {
x: f64,
y: f64,
}
impl Vector2D {
fn new(x: f64, y: f64) -> Self {
Vector2D { x, y }
}
fn magnitude(&self) -> f64 {
(self.x * self.x + self.y * self.y).sqrt()
}
fn normalize(&self) -> Self {
let mag = self.magnitude();
if mag > 0.0 {
Vector2D {
x: self.x / mag,
y: self.y / mag,
}
} else {
*self
}
}
}
// 实现加法
impl Add for Vector2D {
type Output = Vector2D;
fn add(self, other: Vector2D) -> Vector2D {
Vector2D {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
// 实现减法
impl Sub for Vector2D {
type Output = Vector2D;
fn sub(self, other: Vector2D) -> Vector2D {
Vector2D {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
// 实现标量乘法
impl Mul<f64> for Vector2D {
type Output = Vector2D;
fn mul(self, scalar: f64) -> Vector2D {
Vector2D {
x: self.x * scalar,
y: self.y * scalar,
}
}
}
// 实现点积
impl Mul for Vector2D {
type Output = f64;
fn mul(self, other: Vector2D) -> f64 {
self.x * other.x + self.y * other.y
}
}
// 实现标量除法
impl Div<f64> for Vector2D {
type Output = Vector2D;
fn div(self, scalar: f64) -> Vector2D {
Vector2D {
x: self.x / scalar,
y: self.y / scalar,
}
}
}
let v1 = Vector2D::new(3.0, 4.0);
let v2 = Vector2D::new(1.0, 2.0);
println!("v1: {:?}", v1);
println!("v2: {:?}", v2);
let sum = v1 + v2;
println!("v1 + v2: {:?}", sum);
let diff = v1 - v2;
println!("v1 - v2: {:?}", diff);
let scaled = v1 * 2.0;
println!("v1 * 2.0: {:?}", scaled);
let dot_product = v1 * v2;
println!("v1 · v2: {}", dot_product);
let divided = v1 / 2.0;
println!("v1 / 2.0: {:?}", divided);
println!("v1的模长: {:.2}", v1.magnitude());
println!("v1的单位向量: {:?}", v1.normalize());
// 自定义矩阵类型
#[derive(Debug, Clone)]
struct Matrix2x2 {
data: [[f64; 2]; 2],
}
impl Matrix2x2 {
fn new(a: f64, b: f64, c: f64, d: f64) -> Self {
Matrix2x2 {
data: [[a, b], [c, d]],
}
}
fn identity() -> Self {
Matrix2x2::new(1.0, 0.0, 0.0, 1.0)
}
fn determinant(&self) -> f64 {
self.data[0][0] * self.data[1][1] - self.data[0][1] * self.data[1][0]
}
}
impl Add for Matrix2x2 {
type Output = Matrix2x2;
fn add(self, other: Matrix2x2) -> Matrix2x2 {
Matrix2x2 {
data: [
[
self.data[0][0] + other.data[0][0],
self.data[0][1] + other.data[0][1],
],
[
self.data[1][0] + other.data[1][0],
self.data[1][1] + other.data[1][1],
],
],
}
}
}
impl Mul for Matrix2x2 {
type Output = Matrix2x2;
fn mul(self, other: Matrix2x2) -> Matrix2x2 {
Matrix2x2 {
data: [
[
self.data[0][0] * other.data[0][0] + self.data[0][1] * other.data[1][0],
self.data[0][0] * other.data[0][1] + self.data[0][1] * other.data[1][1],
],
[
self.data[1][0] * other.data[0][0] + self.data[1][1] * other.data[1][0],
self.data[1][0] * other.data[0][1] + self.data[1][1] * other.data[1][1],
],
],
}
}
}
let m1 = Matrix2x2::new(1.0, 2.0, 3.0, 4.0);
let m2 = Matrix2x2::new(5.0, 6.0, 7.0, 8.0);
println!("\n矩阵m1: {:?}", m1);
println!("矩阵m2: {:?}", m2);
let sum = m1.clone() + m2.clone();
println!("m1 + m2: {:?}", sum);
let product = m1.clone() * m2.clone();
println!("m1 * m2: {:?}", product);
println!("m1的行列式: {}", m1.determinant());
let identity = Matrix2x2::identity();
println!("单位矩阵: {:?}", identity);
}
fn demonstrate_trait_objects() {
println!("\n特征对象:");
// 定义动物特征
trait Animal {
fn name(&self) -> &str;
fn make_sound(&self) -> &str;
fn describe(&self) -> String {
format!("{} 发出 {} 的声音", self.name(), self.make_sound())
}
}
struct Dog {
name: String,
breed: String,
}
impl Animal for Dog {
fn name(&self) -> &str {
&self.name
}
fn make_sound(&self) -> &str {
"汪汪"
}
fn describe(&self) -> String {
format!("{} 是一只 {} 品种的狗,发出 {} 的声音",
self.name, self.breed, self.make_sound())
}
}
struct Cat {
name: String,
color: String,
}
impl Animal for Cat {
fn name(&self) -> &str {
&self.name
}
fn make_sound(&self) -> &str {
"喵喵"
}
fn describe(&self) -> String {
format!("{} 是一只 {} 颜色的猫,发出 {} 的声音",
self.name, self.color, self.make_sound())
}
}
struct Bird {
name: String,
species: String,
}
impl Animal for Bird {
fn name(&self) -> &str {
&self.name
}
fn make_sound(&self) -> &str {
"啾啾"
}
}
// 使用特征对象
let animals: Vec<Box<dyn Animal>> = vec![
Box::new(Dog {
name: "旺财".to_string(),
breed: "金毛".to_string(),
}),
Box::new(Cat {
name: "咪咪".to_string(),
color: "橘色".to_string(),
}),
Box::new(Bird {
name: "小黄".to_string(),
species: "金丝雀".to_string(),
}),
];
println!("动物园里的动物:");
for animal in &animals {
println!("{}", animal.describe());
}
// 动态分发函数
fn feed_animal(animal: &dyn Animal) {
println!("正在喂食 {}", animal.name());
println!("{} 很开心,发出 {} 的声音", animal.name(), animal.make_sound());
}
println!("\n喂食时间:");
for animal in &animals {
feed_animal(animal.as_ref());
}
// 特征对象的限制和解决方案
trait Cloneable {
fn clone_box(&self) -> Box<dyn Cloneable>;
fn type_name(&self) -> &'static str;
}
#[derive(Clone)]
struct CloneableData {
value: i32,
}
impl Cloneable for CloneableData {
fn clone_box(&self) -> Box<dyn Cloneable> {
Box::new(self.clone())
}
fn type_name(&self) -> &'static str {
"CloneableData"
}
}
let original = CloneableData { value: 42 };
let boxed: Box<dyn Cloneable> = Box::new(original);
let cloned = boxed.clone_box();
println!("\n原始类型: {}", boxed.type_name());
println!("克隆类型: {}", cloned.type_name());
}
fn demonstrate_advanced_patterns() {
println!("\n高级特征模式:");
// 特征别名
trait Printable = std::fmt::Display + std::fmt::Debug;
fn print_both<T: Printable>(value: T) {
println!("Display: {}", value);
println!("Debug: {:?}", value);
}
print_both(42);
print_both("hello");
// 特征的条件实现
struct Wrapper<T>(T);
impl<T> std::fmt::Display for Wrapper<T>
where
T: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Wrapper({})", self.0)
}
}
impl<T> std::fmt::Debug for Wrapper<T>
where
T: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Wrapper({:?})", self.0)
}
}
let wrapped = Wrapper("test");
println!("\n包装器: {}", wrapped);
println!("包装器调试: {:?}", wrapped);
// 特征的默认泛型参数
trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl Add<i32> for Point {
type Output = Point;
fn add(self, scalar: i32) -> Point {
Point {
x: self.x + scalar,
y: self.y + scalar,
}
}
}
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
let sum1 = p1.add(p2);
println!("点相加: {:?}", sum1);
let p3 = Point { x: 5, y: 6 };
let sum2 = p3.add(10);
println!("点加标量: {:?}", sum2);
// 关联常量
trait MathConstants {
const PI: f64;
const E: f64;
fn circle_area(radius: f64) -> f64 {
Self::PI * radius * radius
}
fn exponential(x: f64) -> f64 {
Self::E.powf(x)
}
}
struct StandardMath;
impl MathConstants for StandardMath {
const PI: f64 = 3.14159265359;
const E: f64 = 2.71828182846;
}
struct ApproximateMath;
impl MathConstants for ApproximateMath {
const PI: f64 = 3.14;
const E: f64 = 2.72;
}
println!("\n标准数学常量:");
println!("PI = {}", StandardMath::PI);
println!("E = {}", StandardMath::E);
println!("半径为2的圆面积: {:.2}", StandardMath::circle_area(2.0));
println!("\n近似数学常量:");
println!("PI = {}", ApproximateMath::PI);
println!("E = {}", ApproximateMath::E);
println!("半径为2的圆面积: {:.2}", ApproximateMath::circle_area(2.0));
}
rustc advanced_traits.rs && ./advanced_traits
9.3 生命周期参数
9.3.1 生命周期基础
fn main() {
println!("⏰ 生命周期基础");
println!("===============");
demonstrate_basic_lifetimes();
demonstrate_struct_lifetimes();
demonstrate_method_lifetimes();
demonstrate_static_lifetime();
}
fn demonstrate_basic_lifetimes() {
println!("\n基础生命周期:");
// 基本的生命周期函数
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
let string1 = "hello";
let string2 = "world!";
let result = longest(string1, string2);
println!("最长的字符串: {}", result);
// 不同生命周期的例子
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
println!("在内部作用域中,最长的字符串: {}", result);
}
// result在这里仍然有效,因为它引用的是string1
// 多个生命周期参数
fn first_word<'a, 'b>(s: &'a str, _separator: &'b str) -> &'a str {
s.split_whitespace().next().unwrap_or("")
}
let sentence = "hello world rust";
let sep = " ";
let first = first_word(sentence, sep);
println!("第一个单词: {}", first);
// 生命周期省略规则的例子
fn get_first_char(s: &str) -> Option<char> {
s.chars().next()
}
if let Some(ch) = get_first_char("hello") {
println!("第一个字符: {}", ch);
}
// 返回引用的函数
fn get_slice<'a>(data: &'a [i32], start: usize, end: usize) -> &'a [i32] {
&data[start..end]
}
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let slice = get_slice(&numbers, 2, 6);
println!("切片: {:?}", slice);
// 条件返回引用
fn conditional_ref<'a>(condition: bool, x: &'a str, y: &'a str) -> Option<&'a str> {
if condition {
Some(x)
} else if !y.is_empty() {
Some(y)
} else {
None
}
}
let s1 = "first";
let s2 = "second";
if let Some(result) = conditional_ref(true, s1, s2) {
println!("条件引用结果: {}", result);
}
if let Some(result) = conditional_ref(false, s1, s2) {
println!("条件引用结果: {}", result);
}
}
fn demonstrate_struct_lifetimes() {
println!("\n结构体生命周期:");
// 包含引用的结构体
#[derive(Debug)]
struct ImportantExcerpt<'a> {
part: &'a str,
page: u32,
}
impl<'a> ImportantExcerpt<'a> {
fn new(text: &'a str, page: u32) -> Self {
ImportantExcerpt {
part: text,
page,
}
}
fn get_part(&self) -> &str {
self.part
}
fn get_page(&self) -> u32 {
self.page
}
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("注意!{}", announcement);
self.part
}
}
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().expect("Could not find a '.'")
let excerpt = ImportantExcerpt::new(first_sentence, 1);
println!("摘录: {:?}", excerpt);
println!("部分内容: {}", excerpt.get_part());
println!("页码: {}", excerpt.get_page());
let announced = excerpt.announce_and_return_part("这是一个重要的摘录");
println!("宣布后的部分: {}", announced);
// 多个引用的结构体
#[derive(Debug)]
struct DoubleRef<'a, 'b> {
first: &'a str,
second: &'b str,
}
impl<'a, 'b> DoubleRef<'a, 'b> {
fn new(first: &'a str, second: &'b str) -> Self {
DoubleRef { first, second }
}
fn get_first(&self) -> &'a str {
self.first
}
fn get_second(&self) -> &'b str {
self.second
}
fn get_longer(&self) -> &str {
if self.first.len() > self.second.len() {
self.first
} else {
self.second
}
}
}
let text1 = "short";
let text2 = "much longer text";
let double_ref = DoubleRef::new(text1, text2);
println!("\n双引用: {:?}", double_ref);
println!("第一个: {}", double_ref.get_first());
println!("第二个: {}", double_ref.get_second());
println!("更长的: {}", double_ref.get_longer());
// 嵌套结构体的生命周期
#[derive(Debug)]
struct Container<'a> {
data: &'a str,
}
#[derive(Debug)]
struct Wrapper<'a> {
container: Container<'a>,
metadata: &'a str,
}
let data = "important data";
let metadata = "metadata info";
let container = Container { data };
let wrapper = Wrapper { container, metadata };
println!("\n包装器: {:?}", wrapper);
}
fn demonstrate_method_lifetimes() {
println!("\n方法生命周期:");
struct TextAnalyzer<'a> {
text: &'a str,
}
impl<'a> TextAnalyzer<'a> {
fn new(text: &'a str) -> Self {
TextAnalyzer { text }
}
// 方法的生命周期省略
fn get_text(&self) -> &str {
self.text
}
// 显式生命周期参数
fn find_word<'b>(&self, word: &'b str) -> Option<usize> {
self.text.find(word)
}
// 返回引用的方法
fn get_first_line(&self) -> &str {
self.text.lines().next().unwrap_or("")
}
// 多个生命周期参数的方法
fn compare_with<'b>(&self, other: &'b str) -> &str {
if self.text.len() > other.len() {
self.text
} else {
other
}
}
// 返回新的分析器
fn create_sub_analyzer(&self, start: usize, end: usize) -> TextAnalyzer {
let sub_text = &self.text[start..end];
TextAnalyzer::new(sub_text)
}
}
let text = "Hello, world!\nThis is a test.\nRust is awesome!";
let analyzer = TextAnalyzer::new(text);
println!("原始文本: {}", analyzer.get_text());
println!("第一行: {}", analyzer.get_first_line());
if let Some(pos) = analyzer.find_word("world") {
println!("找到'world'在位置: {}", pos);
}
let other_text = "Short";
let longer = analyzer.compare_with(other_text);
println!("更长的文本: {}", longer);
// 创建子分析器
let sub_analyzer = analyzer.create_sub_analyzer(0, 13);
println!("子分析器文本: {}", sub_analyzer.get_text());
// 链式方法调用
struct ChainableAnalyzer<'a> {
text: &'a str,
processed: String,
}
impl<'a> ChainableAnalyzer<'a> {
fn new(text: &'a str) -> Self {
ChainableAnalyzer {
text,
processed: String::new(),
}
}
fn to_uppercase(mut self) -> Self {
self.processed = self.text.to_uppercase();
self
}
fn add_prefix(mut self, prefix: &str) -> Self {
self.processed = format!("{}{}", prefix, self.processed);
self
}
fn add_suffix(mut self, suffix: &str) -> Self {
self.processed = format!("{}{}", self.processed, suffix);
self
}
fn get_result(&self) -> &str {
&self.processed
}
}
let result = ChainableAnalyzer::new("hello")
.to_uppercase()
.add_prefix(">>> ")
.add_suffix(" <<<")
.get_result();
println!("\n链式处理结果: {}", result);
}
fn demonstrate_static_lifetime() {
println!("\n静态生命周期:");
// 字符串字面量具有'static生命周期
let s: &'static str = "I have a static lifetime.";
println!("静态字符串: {}", s);
// 静态变量
static GLOBAL_DATA: &str = "This is global data";
println!("全局数据: {}", GLOBAL_DATA);
// 返回静态引用的函数
fn get_static_str() -> &'static str {
"This string lives for the entire program duration"
}
let static_ref = get_static_str();
println!("静态引用: {}", static_ref);
// 泄漏内存以获得静态引用
fn leak_string(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
let leaked = leak_string("This will live forever".to_string());
println!("泄漏的字符串: {}", leaked);
// 静态生命周期的结构体
#[derive(Debug)]
struct StaticStruct {
data: &'static str,
}
impl StaticStruct {
fn new(data: &'static str) -> Self {
StaticStruct { data }
}
fn get_data(&self) -> &'static str {
self.data
}
}
let static_struct = StaticStruct::new("Static data");
println!("\n静态结构体: {:?}", static_struct);
println!("静态结构体数据: {}", static_struct.get_data());
// 条件静态生命周期
fn maybe_static(use_static: bool) -> &'static str {
if use_static {
"Static string"
} else {
"Another static string"
}
}
println!("条件静态(true): {}", maybe_static(true));
println!("条件静态(false): {}", maybe_static(false));
// 静态生命周期的常量
const CONSTANT_DATA: &str = "This is constant data";
println!("常量数据: {}", CONSTANT_DATA);
// 静态生命周期的数组
static NUMBERS: [i32; 5] = [1, 2, 3, 4, 5];
println!("静态数组: {:?}", NUMBERS);
fn get_static_slice() -> &'static [i32] {
&NUMBERS
}
let slice = get_static_slice();
println!("静态切片: {:?}", slice);
}
rustc lifetimes_basics.rs && ./lifetimes_basics
9.4 综合示例:通用数据结构
9.4.1 泛型链表实现
fn main() {
println!("🔗 泛型链表实现");
println!("===============");
demonstrate_linked_list();
demonstrate_iterator_implementation();
demonstrate_trait_implementations();
}
fn demonstrate_linked_list() {
println!("\n基础链表操作:");
// 泛型链表节点
#[derive(Debug, Clone)]
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
}
impl<T> Node<T> {
fn new(data: T) -> Self {
Node {
data,
next: None,
}
}
fn with_next(data: T, next: Node<T>) -> Self {
Node {
data,
next: Some(Box::new(next)),
}
}
}
// 泛型链表
#[derive(Debug, Clone)]
struct LinkedList<T> {
head: Option<Box<Node<T>>>,
size: usize,
}
impl<T> LinkedList<T> {
fn new() -> Self {
LinkedList {
head: None,
size: 0,
}
}
fn push_front(&mut self, data: T) {
let new_node = Box::new(Node {
data,
next: self.head.take(),
});
self.head = Some(new_node);
self.size += 1;
}
fn pop_front(&mut self) -> Option<T> {
self.head.take().map(|node| {
self.head = node.next;
self.size -= 1;
node.data
})
}
fn peek_front(&self) -> Option<&T> {
self.head.as_ref().map(|node| &node.data)
}
fn is_empty(&self) -> bool {
self.head.is_none()
}
fn len(&self) -> usize {
self.size
}
fn clear(&mut self) {
self.head = None;
self.size = 0;
}
}
impl<T> LinkedList<T>
where
T: PartialEq,
{
fn contains(&self, item: &T) -> bool {
let mut current = &self.head;
while let Some(node) = current {
if node.data == *item {
return true;
}
current = &node.next;
}
false
}
fn find_position(&self, item: &T) -> Option<usize> {
let mut current = &self.head;
let mut position = 0;
while let Some(node) = current {
if node.data == *item {
return Some(position);
}
current = &node.next;
position += 1;
}
None
}
fn remove(&mut self, item: &T) -> bool {
if self.head.is_none() {
return false;
}
// 检查头节点
if let Some(ref head_node) = self.head {
if head_node.data == *item {
self.head = head_node.next.clone();
self.size -= 1;
return true;
}
}
// 检查其他节点
let mut current = &mut self.head;
while let Some(ref mut node) = current {
if let Some(ref next_node) = node.next {
if next_node.data == *item {
node.next = next_node.next.clone();
self.size -= 1;
return true;
}
}
current = &mut node.next;
}
false
}
}
// 测试整数链表
let mut int_list = LinkedList::new();
println!("创建空链表,长度: {}", int_list.len());
int_list.push_front(3);
int_list.push_front(2);
int_list.push_front(1);
println!("添加元素后: {:?}", int_list);
println!("链表长度: {}", int_list.len());
if let Some(front) = int_list.peek_front() {
println!("头部元素: {}", front);
}
println!("包含2: {}", int_list.contains(&2));
println!("包含5: {}", int_list.contains(&5));
if let Some(pos) = int_list.find_position(&2) {
println!("元素2的位置: {}", pos);
}
if let Some(popped) = int_list.pop_front() {
println!("弹出元素: {}", popped);
}
println!("弹出后: {:?}", int_list);
int_list.remove(&2);
println!("移除2后: {:?}", int_list);
// 测试字符串链表
let mut string_list = LinkedList::new();
string_list.push_front("world".to_string());
string_list.push_front("hello".to_string());
println!("\n字符串链表: {:?}", string_list);
while let Some(item) = string_list.pop_front() {
println!("弹出: {}", item);
}
println!("清空后是否为空: {}", string_list.is_empty());
}
fn demonstrate_iterator_implementation() {
println!("\n迭代器实现:");
#[derive(Debug, Clone)]
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
}
#[derive(Debug, Clone)]
struct LinkedList<T> {
head: Option<Box<Node<T>>>,
size: usize,
}
impl<T> LinkedList<T> {
fn new() -> Self {
LinkedList {
head: None,
size: 0,
}
}
fn push_front(&mut self, data: T) {
let new_node = Box::new(Node {
data,
next: self.head.take(),
});
self.head = Some(new_node);
self.size += 1;
}
}
// 实现IntoIterator特征
impl<T> IntoIterator for LinkedList<T> {
type Item = T;
type IntoIter = LinkedListIntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
LinkedListIntoIter {
current: self.head,
}
}
}
// 拥有所有权的迭代器
struct LinkedListIntoIter<T> {
current: Option<Box<Node<T>>>,
}
impl<T> Iterator for LinkedListIntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.current.take().map(|node| {
self.current = node.next;
node.data
})
}
}
// 借用迭代器
impl<T> LinkedList<T> {
fn iter(&self) -> LinkedListIter<T> {
LinkedListIter {
current: self.head.as_deref(),
}
}
}
struct LinkedListIter<'a, T> {
current: Option<&'a Node<T>>,
}
impl<'a, T> Iterator for LinkedListIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.current.map(|node| {
self.current = node.next.as_deref();
&node.data
})
}
}
// 可变借用迭代器
impl<T> LinkedList<T> {
fn iter_mut(&mut self) -> LinkedListIterMut<T> {
LinkedListIterMut {
current: self.head.as_deref_mut(),
}
}
}
struct LinkedListIterMut<'a, T> {
current: Option<&'a mut Node<T>>,
}
impl<'a, T> Iterator for LinkedListIterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
self.current.take().map(|node| {
self.current = node.next.as_deref_mut();
&mut node.data
})
}
}
// 测试迭代器
let mut list = LinkedList::new();
list.push_front(3);
list.push_front(2);
list.push_front(1);
println!("使用借用迭代器:");
for item in list.iter() {
println!("{}", item);
}
println!("\n使用可变借用迭代器(每个元素乘以2):");
for item in list.iter_mut() {
*item *= 2;
}
for item in list.iter() {
println!("{}", item);
}
println!("\n使用拥有所有权的迭代器:");
for item in list {
println!("{}", item);
}
// 函数式编程风格
let mut list2 = LinkedList::new();
list2.push_front(5);
list2.push_front(4);
list2.push_front(3);
list2.push_front(2);
list2.push_front(1);
let sum: i32 = list2.iter().sum();
println!("\n链表元素和: {}", sum);
let even_count = list2.iter().filter(|&&x| x % 2 == 0).count();
println!("偶数个数: {}", even_count);
let doubled: Vec<i32> = list2.iter().map(|&x| x * 2).collect();
println!("每个元素乘以2: {:?}", doubled);
}
fn demonstrate_trait_implementations() {
println!("\n特征实现:");
#[derive(Debug, Clone)]
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
}
#[derive(Debug, Clone)]
struct LinkedList<T> {
head: Option<Box<Node<T>>>,
size: usize,
}
impl<T> LinkedList<T> {
fn new() -> Self {
LinkedList {
head: None,
size: 0,
}
}
fn push_front(&mut self, data: T) {
let new_node = Box::new(Node {
data,
next: self.head.take(),
});
self.head = Some(new_node);
self.size += 1;
}
fn len(&self) -> usize {
self.size
}
fn is_empty(&self) -> bool {
self.head.is_none()
}
}
// 实现Default特征
impl<T> Default for LinkedList<T> {
fn default() -> Self {
Self::new()
}
}
// 实现PartialEq特征
impl<T: PartialEq> PartialEq for LinkedList<T> {
fn eq(&self, other: &Self) -> bool {
if self.size != other.size {
return false;
}
let mut self_current = &self.head;
let mut other_current = &other.head;
while let (Some(self_node), Some(other_node)) = (self_current, other_current) {
if self_node.data != other_node.data {
return false;
}
self_current = &self_node.next;
other_current = &other_node.next;
}
true
}
}
// 实现Display特征
impl<T: std::fmt::Display> std::fmt::Display for LinkedList<T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "[")?;
let mut current = &self.head;
let mut first = true;
while let Some(node) = current {
if !first {
write!(f, ", ")?;
}
write!(f, "{}", node.data)?;
current = &node.next;
first = false;
}
write!(f, "]")
}
}
// 实现FromIterator特征
impl<T> std::iter::FromIterator<T> for LinkedList<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut list = LinkedList::new();
let mut items: Vec<T> = iter.into_iter().collect();
// 反向添加以保持顺序
while let Some(item) = items.pop() {
list.push_front(item);
}
list
}
}
// 实现Extend特征
impl<T> std::iter::Extend<T> for LinkedList<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for item in iter {
self.push_front(item);
}
}
}
// 测试特征实现
let list1: LinkedList<i32> = LinkedList::default();
println!("默认链表: {}", list1);
let list2: LinkedList<i32> = (1..=5).collect();
println!("从迭代器创建: {}", list2);
let mut list3 = LinkedList::new();
list3.push_front(1);
list3.push_front(2);
list3.push_front(3);
let mut list4 = LinkedList::new();
list4.push_front(1);
list4.push_front(2);
list4.push_front(3);
println!("\nlist3: {}", list3);
println!("list4: {}", list4);
println!("list3 == list4: {}", list3 == list4);
list4.push_front(4);
println!("添加元素后 list3 == list4: {}", list3 == list4);
let mut list5 = LinkedList::new();
list5.extend(vec![10, 20, 30]);
println!("\n扩展后的链表: {}", list5);
// 链式操作
let result: LinkedList<i32> = (1..=10)
.filter(|&x| x % 2 == 0)
.map(|x| x * x)
.collect();
println!("偶数平方链表: {}", result);
}
rustc generic_linked_list.rs && ./generic_linked_list
9.4.2 泛型缓存系统
use std::collections::HashMap;
use std::hash::Hash;
use std::time::{Duration, Instant};
fn main() {
println!("💾 泛型缓存系统");
println!("===============");
demonstrate_basic_cache();
demonstrate_ttl_cache();
demonstrate_lru_cache();
demonstrate_cache_traits();
}
fn demonstrate_basic_cache() {
println!("\n基础缓存:");
// 基础泛型缓存
#[derive(Debug)]
struct Cache<K, V> {
data: HashMap<K, V>,
max_size: usize,
}
impl<K, V> Cache<K, V>
where
K: Eq + Hash + Clone,
V: Clone,
{
fn new(max_size: usize) -> Self {
Cache {
data: HashMap::new(),
max_size,
}
}
fn get(&self, key: &K) -> Option<&V> {
self.data.get(key)
}
fn put(&mut self, key: K, value: V) -> Option<V> {
if self.data.len() >= self.max_size && !self.data.contains_key(&key) {
// 简单的清理策略:清除第一个元素
if let Some(first_key) = self.data.keys().next().cloned() {
self.data.remove(&first_key);
}
}
self.data.insert(key, value)
}
fn remove(&mut self, key: &K) -> Option<V> {
self.data.remove(key)
}
fn contains_key(&self, key: &K) -> bool {
self.data.contains_key(key)
}
fn len(&self) -> usize {
self.data.len()
}
fn is_empty(&self) -> bool {
self.data.is_empty()
}
fn clear(&mut self) {
self.data.clear();
}
fn keys(&self) -> impl Iterator<Item = &K> {
self.data.keys()
}
fn values(&self) -> impl Iterator<Item = &V> {
self.data.values()
}
}
// 测试基础缓存
let mut cache = Cache::new(3);
cache.put("key1".to_string(), 100);
cache.put("key2".to_string(), 200);
cache.put("key3".to_string(), 300);
println!("缓存大小: {}", cache.len());
if let Some(value) = cache.get(&"key2".to_string()) {
println!("key2的值: {}", value);
}
println!("包含key1: {}", cache.contains_key(&"key1".to_string()));
// 添加第四个元素,应该触发清理
cache.put("key4".to_string(), 400);
println!("添加key4后,缓存大小: {}", cache.len());
println!("所有键:");
for key in cache.keys() {
println!(" {}", key);
}
println!("所有值:");
for value in cache.values() {
println!(" {}", value);
}
}
fn demonstrate_ttl_cache() {
println!("\nTTL缓存(生存时间):");
// 带TTL的缓存项
#[derive(Debug, Clone)]
struct CacheItem<V> {
value: V,
expires_at: Instant,
}
impl<V> CacheItem<V> {
fn new(value: V, ttl: Duration) -> Self {
CacheItem {
value,
expires_at: Instant::now() + ttl,
}
}
fn is_expired(&self) -> bool {
Instant::now() > self.expires_at
}
}
// TTL缓存
#[derive(Debug)]
struct TTLCache<K, V> {
data: HashMap<K, CacheItem<V>>,
default_ttl: Duration,
max_size: usize,
}
impl<K, V> TTLCache<K, V>
where
K: Eq + Hash + Clone,
V: Clone,
{
fn new(max_size: usize, default_ttl: Duration) -> Self {
TTLCache {
data: HashMap::new(),
default_ttl,
max_size,
}
}
fn get(&mut self, key: &K) -> Option<&V> {
self.cleanup_expired();
if let Some(item) = self.data.get(key) {
if !item.is_expired() {
return Some(&item.value);
} else {
self.data.remove(key);
}
}
None
}
fn put(&mut self, key: K, value: V) -> Option<V> {
self.put_with_ttl(key, value, self.default_ttl)
}
fn put_with_ttl(&mut self, key: K, value: V, ttl: Duration) -> Option<V> {
self.cleanup_expired();
if self.data.len() >= self.max_size && !self.data.contains_key(&key) {
// 移除最旧的项
if let Some(oldest_key) = self.find_oldest_key() {
self.data.remove(&oldest_key);
}
}
let item = CacheItem::new(value, ttl);
self.data.insert(key, item).map(|old_item| old_item.value)
}
fn remove(&mut self, key: &K) -> Option<V> {
self.data.remove(key).map(|item| item.value)
}
fn cleanup_expired(&mut self) {
let expired_keys: Vec<K> = self.data
.iter()
.filter(|(_, item)| item.is_expired())
.map(|(key, _)| key.clone())
.collect();
for key in expired_keys {
self.data.remove(&key);
}
}
fn find_oldest_key(&self) -> Option<K> {
self.data
.iter()
.min_by_key(|(_, item)| item.expires_at)
.map(|(key, _)| key.clone())
}
fn len(&self) -> usize {
self.data.len()
}
fn is_empty(&self) -> bool {
self.data.is_empty()
}
}
// 测试TTL缓存
let mut ttl_cache = TTLCache::new(5, Duration::from_millis(100));
ttl_cache.put("short".to_string(), "短期数据".to_string());
ttl_cache.put_with_ttl(
"long".to_string(),
"长期数据".to_string(),
Duration::from_secs(10),
);
println!("立即获取short: {:?}", ttl_cache.get(&"short".to_string()));
println!("立即获取long: {:?}", ttl_cache.get(&"long".to_string()));
// 模拟时间流逝
std::thread::sleep(Duration::from_millis(150));
println!("150ms后获取short: {:?}", ttl_cache.get(&"short".to_string()));
println!("150ms后获取long: {:?}", ttl_cache.get(&"long".to_string()));
println!("清理后缓存大小: {}", ttl_cache.len());
}
fn demonstrate_lru_cache() {
println!("\nLRU缓存(最近最少使用):");
use std::collections::VecDeque;
// LRU缓存项
#[derive(Debug, Clone)]
struct LRUItem<K, V> {
key: K,
value: V,
access_time: Instant,
}
// LRU缓存
#[derive(Debug)]
struct LRUCache<K, V> {
data: HashMap<K, V>,
access_order: VecDeque<K>,
max_size: usize,
}
impl<K, V> LRUCache<K, V>
where
K: Eq + Hash + Clone,
V: Clone,
{
fn new(max_size: usize) -> Self {
LRUCache {
data: HashMap::new(),
access_order: VecDeque::new(),
max_size,
}
}
fn get(&mut self, key: &K) -> Option<&V> {
if self.data.contains_key(key) {
self.move_to_front(key);
self.data.get(key)
} else {
None
}
}
fn put(&mut self, key: K, value: V) -> Option<V> {
if self.data.contains_key(&key) {
// 更新现有键
self.move_to_front(&key);
self.data.insert(key, value)
} else {
// 添加新键
if self.data.len() >= self.max_size {
self.evict_lru();
}
self.access_order.push_front(key.clone());
self.data.insert(key, value)
}
}
fn remove(&mut self, key: &K) -> Option<V> {
if let Some(value) = self.data.remove(key) {
self.access_order.retain(|k| k != key);
Some(value)
} else {
None
}
}
fn move_to_front(&mut self, key: &K) {
// 移除键并添加到前面
self.access_order.retain(|k| k != key);
self.access_order.push_front(key.clone());
}
fn evict_lru(&mut self) {
if let Some(lru_key) = self.access_order.pop_back() {
self.data.remove(&lru_key);
}
}
fn len(&self) -> usize {
self.data.len()
}
fn is_empty(&self) -> bool {
self.data.is_empty()
}
fn get_access_order(&self) -> Vec<&K> {
self.access_order.iter().collect()
}
}
// 测试LRU缓存
let mut lru_cache = LRUCache::new(3);
lru_cache.put("a".to_string(), 1);
lru_cache.put("b".to_string(), 2);
lru_cache.put("c".to_string(), 3);
println!("初始访问顺序: {:?}", lru_cache.get_access_order());
// 访问'a',应该移到前面
lru_cache.get(&"a".to_string());
println!("访问'a'后的顺序: {:?}", lru_cache.get_access_order());
// 添加新元素,应该移除最少使用的'b'
lru_cache.put("d".to_string(), 4);
println!("添加'd'后的顺序: {:?}", lru_cache.get_access_order());
println!("尝试获取'b': {:?}", lru_cache.get(&"b".to_string()));
println!("获取'c': {:?}", lru_cache.get(&"c".to_string()));
println!("最终访问顺序: {:?}", lru_cache.get_access_order());
}
fn demonstrate_cache_traits() {
println!("\n缓存特征:");
// 定义缓存特征
trait Cache<K, V> {
fn get(&mut self, key: &K) -> Option<&V>;
fn put(&mut self, key: K, value: V) -> Option<V>;
fn remove(&mut self, key: &K) -> Option<V>;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn clear(&mut self);
}
// 统计缓存装饰器
#[derive(Debug)]
struct StatsCache<C> {
cache: C,
hits: usize,
misses: usize,
puts: usize,
removes: usize,
}
impl<C> StatsCache<C> {
fn new(cache: C) -> Self {
StatsCache {
cache,
hits: 0,
misses: 0,
puts: 0,
removes: 0,
}
}
fn hit_rate(&self) -> f64 {
let total = self.hits + self.misses;
if total == 0 {
0.0
} else {
self.hits as f64 / total as f64
}
}
fn stats(&self) -> (usize, usize, usize, usize, f64) {
(self.hits, self.misses, self.puts, self.removes, self.hit_rate())
}
}
impl<K, V, C> Cache<K, V> for StatsCache<C>
where
C: Cache<K, V>,
{
fn get(&mut self, key: &K) -> Option<&V> {
match self.cache.get(key) {
Some(value) => {
self.hits += 1;
Some(value)
}
None => {
self.misses += 1;
None
}
}
}
fn put(&mut self, key: K, value: V) -> Option<V> {
self.puts += 1;
self.cache.put(key, value)
}
fn remove(&mut self, key: &K) -> Option<V> {
self.removes += 1;
self.cache.remove(key)
}
fn len(&self) -> usize {
self.cache.len()
}
fn clear(&mut self) {
self.cache.clear();
}
}
// 简单的HashMap缓存实现
#[derive(Debug)]
struct SimpleCache<K, V> {
data: HashMap<K, V>,
max_size: usize,
}
impl<K, V> SimpleCache<K, V>
where
K: Eq + Hash + Clone,
{
fn new(max_size: usize) -> Self {
SimpleCache {
data: HashMap::new(),
max_size,
}
}
}
impl<K, V> Cache<K, V> for SimpleCache<K, V>
where
K: Eq + Hash + Clone,
{
fn get(&mut self, key: &K) -> Option<&V> {
self.data.get(key)
}
fn put(&mut self, key: K, value: V) -> Option<V> {
if self.data.len() >= self.max_size && !self.data.contains_key(&key) {
if let Some(first_key) = self.data.keys().next().cloned() {
self.data.remove(&first_key);
}
}
self.data.insert(key, value)
}
fn remove(&mut self, key: &K) -> Option<V> {
self.data.remove(key)
}
fn len(&self) -> usize {
self.data.len()
}
fn clear(&mut self) {
self.data.clear();
}
}
// 测试统计缓存
let simple_cache = SimpleCache::new(5);
let mut stats_cache = StatsCache::new(simple_cache);
// 执行一些操作
stats_cache.put("key1".to_string(), "value1".to_string());
stats_cache.put("key2".to_string(), "value2".to_string());
stats_cache.put("key3".to_string(), "value3".to_string());
stats_cache.get(&"key1".to_string()); // 命中
stats_cache.get(&"key2".to_string()); // 命中
stats_cache.get(&"key4".to_string()); // 未命中
stats_cache.get(&"key5".to_string()); // 未命中
stats_cache.get(&"key1".to_string()); // 命中
stats_cache.remove(&"key2".to_string());
let (hits, misses, puts, removes, hit_rate) = stats_cache.stats();
println!("缓存统计:");
println!(" 命中: {}", hits);
println!(" 未命中: {}", misses);
println!(" 放入: {}", puts);
println!(" 移除: {}", removes);
println!(" 命中率: {:.2}%", hit_rate * 100.0);
println!(" 当前大小: {}", stats_cache.len());
}
rustc generic_cache.rs && ./generic_cache
9.5 本章小结
在本章中,我们深入学习了Rust的泛型和特征系统:
🎯 主要内容回顾
泛型基础
- 泛型函数的定义和使用
- 泛型结构体和枚举
- 泛型方法和关联函数
- 泛型约束和where子句
特征系统
- 特征的定义和实现
- 默认实现和特征边界
- 特征对象和动态分发
- 关联类型和关联常量
高级特征模式
- 操作符重载
- 特征别名和条件实现
- 默认泛型参数
- 特征的组合和继承
生命周期参数
- 生命周期的基本概念
- 结构体和方法中的生命周期
- 静态生命周期
- 生命周期省略规则
综合应用
- 泛型链表的完整实现
- 泛型缓存系统
- 迭代器特征的实现
- 实际项目中的应用模式
💡 核心概念
- 零成本抽象:泛型在编译时被单态化,运行时无额外开销
- 类型安全:编译时确保类型正确性
- 代码复用:一套代码适用于多种类型
- 特征边界:约束泛型类型必须实现特定行为
- 生命周期:确保引用的有效性和内存安全
🚀 最佳实践
- 合理使用泛型约束,避免过度泛化
- 优先使用特征对象处理异构集合
- 利用关联类型简化复杂的泛型签名
- 遵循生命周期省略规则,减少显式标注
- 实现标准库特征提高代码的互操作性
📚 下一章预告
在下一章《集合类型》中,我们将学习:
- 🔢 向量(Vec):动态数组的使用和优化
- 🗂️ 哈希映射(HashMap):键值对存储和查找
- 📚 哈希集合(HashSet):唯一值的集合操作
- 🔗 其他集合类型:VecDeque、BTreeMap等
- 🎯 集合的选择和性能:不同场景下的最佳选择
- 🛠️ 自定义集合:实现自己的数据结构
🎯 本章练习
练习1:泛型栈实现
实现一个泛型栈数据结构,包含以下功能:
- push:压入元素
- pop:弹出元素
- peek:查看栈顶元素
- is_empty:检查是否为空
- 实现Iterator特征
练习2:特征组合
定义以下特征并为自定义类型实现:
- Drawable:可绘制特征
- Movable:可移动特征
- GameObject:游戏对象特征(组合上述特征)
- 创建一个游戏对象管理器
练习3:生命周期实践
实现一个文本分析器,包含: - 存储文本引用的结构体 - 返回文本片段的方法 - 比较不同文本的方法 - 正确处理生命周期参数
练习4:泛型配置系统
设计一个泛型配置系统: - 支持不同类型的配置值 - 提供类型安全的获取方法 - 支持默认值和验证 - 实现序列化和反序列化
练习5:高级缓存
扩展本章的缓存示例: - 实现多级缓存 - 添加缓存预热功能 - 支持异步操作 - 提供监控和统计接口
通过这些练习,你将更深入地理解泛型和特征的强大功能,为后续的高级主题打下坚实基础!