FnOnce Trait 获取所有权
核心概念
FnOnce 是三个闭包 trait 中最宽松的一个,表示闭包可以消耗(获取所有权)捕获的变量。FnOnce 通过 self(按值)调用,所以闭包本身在调用后也被消耗,只能调用一次。所有闭包都至少实现 FnOnce,因此 FnOnce 能接受任何闭包。当一个函数参数只需要调用闭包一次时,使用 FnOnce 作为 trait bound 最为合适,因为它对调用者的限制最小。
fn main() {
let data = vec![1, 2, 3, 4, 5];
// 这个闭包消耗了 data(通过 drop 或移动)
let consume = || {
let sum: i32 = data.into_iter().sum(); // into_iter 消耗 data
println!("总和: {}", sum);
};
consume();
// consume(); // 编译错误:FnOnce 只能调用一次
// data 也不能再使用了
}FnOnce 的调用规则
// FnOnce 通过 self(按值)调用
// 调用一次后闭包本身被消耗
fn call_once(f: impl FnOnce() -> String) -> String {
f() // 消耗 f,只能调用一次
// f() // 编译错误:f 已经被消耗
}
fn call_once_with_arg(f: impl FnOnce(i32) -> String, arg: i32) -> String {
f(arg)
}
fn main() {
// 消耗捕获变量的闭包
let name = String::from("Rust");
let result = call_once(|| {
format!("Hello, {}!", name) // name 被移入返回值
});
println!("{}", result);
// 即使是 Fn 闭包也可以传给 FnOnce 参数
let factor = 3;
let result = call_once_with_arg(|x| format!("{} * {} = {}", x, factor, x * factor), 7);
println!("{}", result);
}三种闭包 trait 的继承关系
// FnOnce 是最宽松的,所有闭包都实现它
// Fn: FnMut: FnOnce
// Fn ⊂ FnMut ⊂ FnOnce
fn needs_once(f: impl FnOnce()) {
f();
}
fn needs_mut(mut f: impl FnMut()) {
f();
f();
}
fn needs_fn(f: impl Fn()) {
f();
f();
f();
}
fn main() {
// Fn 闭包可以传给任何参数
let x = 42;
let fn_closure = || println!("Fn: {}", x);
needs_once(fn_closure);
let fn_closure2 = || println!("Fn: {}", x);
needs_mut(fn_closure2);
let fn_closure3 = || println!("Fn: {}", x);
needs_fn(fn_closure3);
// FnMut 闭包可以传给 FnOnce 和 FnMut
let mut count = 0;
let fn_mut_closure = || { count += 1; };
needs_once(fn_mut_closure);
// needs_fn(fn_mut_closure); // 编译错误:FnMut 不实现 Fn
// FnOnce 闭包只能传给 FnOnce
let data = String::from("hello");
let fn_once_closure = || { drop(data); };
needs_once(fn_once_closure);
// needs_mut(fn_once_closure); // 编译错误
// needs_fn(fn_once_closure); // 编译错误
}| 闭包类型 | 可传给 FnOnce | 可传给 FnMut | 可传给 Fn |
|---|---|---|---|
| Fn 闭包 | 可以 | 可以 | 可以 |
| FnMut 闭包 | 可以 | 可以 | 不可以 |
| FnOnce 闭包 | 可以 | 不可以 | 不可以 |
典型的 FnOnce 场景
use std::thread;
fn main() {
// 场景1:thread::spawn 接受 FnOnce
let message = String::from("来自主线程");
let handle = thread::spawn(move || {
// 线程闭包只执行一次
println!("{}", message);
message.len() // 返回值
});
let len = handle.join().unwrap();
println!("消息长度: {}", len);
// 场景2:Option::map 接受 FnOnce
let name: Option<String> = Some(String::from("张三"));
let greeting = name.map(|n| format!("你好, {}!", n)); // n 被消耗
println!("{:?}", greeting);
// name 已经被 map 消耗了
// 场景3:unwrap_or_else 接受 FnOnce
let value: Result<i32, String> = Err(String::from("未找到"));
let result = value.unwrap_or_else(|err| {
println!("错误: {}", err); // err 被消耗
-1
});
println!("结果: {}", result);
// 场景4:自定义的一次性操作
let config = String::from("production");
let setup = move || {
println!("初始化环境: {}", config);
// 返回初始化结果
config.to_uppercase()
};
let env = setup();
println!("环境: {}", env);
// setup(); // 编译错误:已经调用过了
}FnOnce 与返回值
// FnOnce 常用于只需要执行一次并返回结果的场景
fn execute<T>(f: impl FnOnce() -> T) -> T {
f()
}
fn execute_with<A, R>(f: impl FnOnce(A) -> R, arg: A) -> R {
f(arg)
}
// 延迟初始化
fn lazy_init<T>(initializer: impl FnOnce() -> T) -> T {
println!("执行初始化...");
let value = initializer();
println!("初始化完成");
value
}
fn main() {
// 简单执行
let result = execute(|| 42 * 2);
println!("结果: {}", result);
// 带参数执行
let greeting = execute_with(
|name: String| format!("Hello, {}!", name),
String::from("World"),
);
println!("{}", greeting);
// 延迟初始化
let data = lazy_init(|| {
let mut v = Vec::new();
for i in 0..10 {
v.push(i * i);
}
v
});
println!("数据: {:?}", data);
// 条件执行
let expensive = true;
if expensive {
let result = lazy_init(|| {
// 模拟耗时操作
String::from("昂贵的计算结果")
});
println!("计算: {}", result);
}
}基本示例
用 FnOnce 构建一个任务调度系统:
struct Task {
name: String,
action: Box<dyn FnOnce() -> String>,
}
impl Task {
fn new<F>(name: &str, action: F) -> Self
where
F: FnOnce() -> String + 'static,
{
Task {
name: name.to_string(),
action: Box::new(action),
}
}
// 执行任务(消耗 self)
fn run(self) -> String {
println!("执行任务: {}", self.name);
let result = (self.action)();
println!(" 结果: {}", result);
result
}
}
struct TaskQueue {
tasks: Vec<Task>,
}
impl TaskQueue {
fn new() -> Self {
TaskQueue { tasks: Vec::new() }
}
fn add<F>(&mut self, name: &str, action: F)
where
F: FnOnce() -> String + 'static,
{
self.tasks.push(Task::new(name, action));
}
// 执行所有任务(消耗队列)
fn run_all(self) -> Vec<String> {
println!("=== 开始执行任务队列 ({} 个任务) ===", self.tasks.len());
let mut results = Vec::new();
for task in self.tasks {
let result = task.run();
results.push(result);
}
println!("=== 全部完成 ===");
results
}
}
fn main() {
let mut queue = TaskQueue::new();
// 每个任务的闭包可以捕获不同的数据
let user_data = String::from("张三");
queue.add("创建用户", move || {
format!("用户 {} 已创建", user_data)
});
let config = vec!["debug=true", "port=8080"];
queue.add("加载配置", move || {
format!("配置已加载: {:?}", config)
});
queue.add("初始化数据库", || {
String::from("数据库连接成功")
});
let items = vec![1, 2, 3, 4, 5];
queue.add("处理数据", move || {
let sum: i32 = items.into_iter().sum();
format!("数据总和: {}", sum)
});
// 执行所有任务
let results = queue.run_all();
println!("\n所有结果:");
for (i, result) in results.iter().enumerate() {
println!(" [{}] {}", i + 1, result);
}
}常见问题
问题一:为什么函数参数优先用 FnOnce?
FnOnce 是最宽松的约束——所有闭包都实现它。如果函数只需要调用闭包一次,用 FnOnce 可以接受任何闭包(Fn、FnMut、FnOnce),给调用者最大的自由度。
问题二:FnOnce 闭包可以存储在集合中吗?
可以用 Box<dyn FnOnce()> 存储,但调用时需要从集合中取出(因为调用会消耗闭包)。
问题三:move 闭包一定是 FnOnce 吗?
不一定。move 只影响捕获方式。如果 move 闭包只读取数据,它实现 Fn;如果修改数据,实现 FnMut;只有消耗数据时才仅实现 FnOnce。
问题四:标准库哪些方法接受 FnOnce?
thread::spawn、Option::map、Result::map、unwrap_or_else、and_then 等只需要调用一次闭包的方法。
适用场景
- 线程创建:
thread::spawn只执行一次闭包 - Option/Result 方法:
map、and_then、unwrap_or_else - 一次性初始化:延迟初始化、配置加载
- 任务调度:每个任务只执行一次
注意事项
FnOnce闭包只能调用一次,调用后被消耗- 所有闭包都实现
FnOnce - 函数只调用一次闭包时优先用
FnOnce作为 bound Box<dyn FnOnce()>用于存储一次性闭包move不决定闭包是 FnOnce,闭包体是否消耗变量才决定thread::spawn要求FnOnce + Send + 'static
总结
FnOnce 是最宽松的闭包 trait,通过 self(按值)调用,闭包调用后被消耗,只能调用一次。所有闭包都至少实现 FnOnce(Fn ⊂ FnMut ⊂ FnOnce),所以 FnOnce 参数可以接受任何闭包。当函数只需要调用闭包一次时,优先使用 FnOnce 作为 trait bound,给调用者最大自由度。典型应用包括 thread::spawn、Option::map、unwrap_or_else、一次性初始化、任务调度等。move 关键字不决定闭包是否为 FnOnce,关键是闭包体是否消耗了捕获的变量。