【发布时间】:2018-02-09 02:04:38
【问题描述】:
fn main() {
let s = Some("xyz".to_string()); //compiler error
let foo = Box::new(|| s) as Box<Fn() -> Option<String>>; //ok
let bar = Box::new(|| Some("xyz".to_string())) as Box<Fn() -> Option<String>>;
println!("{:?}", foo());
println!("{:?}", bar());
}
给出错误
error[E0277]: the trait bound `[closure@src/main.rs:5:24: 5:28 s:std::option::Option<std::string::String>]: std::ops::Fn<()>` is not satisfied
--> src/main.rs:5:15
|
5 | let foo = Box::new(|| s) as Box<Fn() -> Option<String>>;
| ^^^^^^^^^^^^^^ the trait `std::ops::Fn<()>` is not implemented for `[closure@src/main.rs:5:24: 5:28 s:std::option::Option<std::string::String>]`
|
= note: required for the cast to the object type `std::ops::Fn() -> std::option::Option<std::string::String>`
error: aborting due to previous error
Trait std::ops::Fn 状态的文档:
Fn 由闭包自动实现,这些闭包只对捕获的变量进行不可变引用或根本不捕获任何东西,
s 不是可变的,但它不是参考,我正在移动它。
如果我调用s.clone(),编译器错误就会消失,但在我的实际情况下,我想避免这种情况。
如果我使用 FnMut FnOnce 会出现同样的错误,即使它是盒装的,也会抱怨不知道大小。
有没有办法让我可以使用移动的数据?
【问题讨论】:
标签: rust