Skip to content

Rust 智能指针与 Trait

let b = Box::new(5);
println!("b = {}", b);
// 递归类型必须使用 Box
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
let list = Cons(1, Box::new(Cons(2, Box::new(Nil))));
use std::rc::Rc;
let a = Rc::new(5);
let b = Rc::clone(&a); // 引用计数 +1
let c = Rc::clone(&a); // 引用计数 +1
println!("引用计数: {}", Rc::strong_count(&a)); // 3

Arc<T> — 原子引用计数(线程安全)

Section titled “Arc<T> — 原子引用计数(线程安全)”
use std::sync::Arc;
use std::thread;
let data = Arc::new(vec![1, 2, 3]);
for _ in 0..3 {
let data = Arc::clone(&data);
thread::spawn(move || {
println!("{:?}", *data);
});
}
trait Summary {
fn summarize(&self) -> String;
// 默认实现
fn preview(&self) -> String {
format!("{}...", &self.summarize()[..20.min(self.summarize().len())])
}
}
struct Article { title: String, content: String }
impl Summary for Article {
fn summarize(&self) -> String {
format!("{}: {}", self.title, self.content)
}
}
fn print_summary(item: &dyn Summary) {
println!("{}", item.summarize());
}
let article = Article {
title: "Rust".into(),
content: "Learn Rust".into(),
};
print_summary(&article);
Trait用途
Debug格式化调试输出 {:?}
Clone显式深拷贝
Copy隐式位拷贝(栈上类型)
From/Into类型转换
Display格式化用户输出 {}
Iterator迭代器
Send/Sync线程安全标记