我试图运行官方文档中的FnBox
示例,但它抛出了一个错误:
error[E0432]: unresolved import `std::boxed::FnBox`
--> src/main.rs:4:5
|
4 | use std::boxed::FnBox;
| ^^^^^^^^^^^^^^^^^ no `FnBox` in `boxed`
Run Code Online (Sandbox Code Playgroud)
使用 rust playground很容易得到这个错误,我在本地也得到了同样的错误。
实际上我在本地找到了一些来自 std 的声明:
#[rustc_paren_sugar]
#[unstable(feature = "fnbox",
reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
pub trait FnBox<A>: FnOnce<A> {
/// Performs the call operation.
fn call_box(self: Box<Self>, args: A) -> Self::Output;
}
#[unstable(feature = "fnbox",
reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
impl<A, F> FnBox<A> for F
where F: FnOnce<A>
{
fn call_box(self: Box<F>, args: A) -> F::Output {
self.call_once(args)
}
}
Run Code Online (Sandbox Code Playgroud)
但是还是有错误。
FnBox
一直没有稳定下来。它更像是一种当你想要的时候使用的 hack,Box<dyn FnOnce()>
但这种类型并没有用来实现FnOnce
它自己。
因为自 Rust 1.35 起Box<dyn FnOnce()>
实现FnOnce
,FnBox
已在 Rust 1.37 中移除。
的所有用法Box<FnBox<_>>
都可以替换为Box<FnOnce<_>>
,例如旧文档示例:
use std::collections::HashMap;
fn make_map() -> HashMap<i32, Box<dyn FnOnce() -> i32>> {
let mut map: HashMap<i32, Box<dyn FnOnce() -> i32>> = HashMap::new();
map.insert(1, Box::new(|| 22));
map.insert(2, Box::new(|| 44));
map
}
fn main() {
let mut map = make_map();
for i in &[1, 2] {
let f = map.remove(&i).unwrap();
assert_eq!(f(), i * 22);
}
}
Run Code Online (Sandbox Code Playgroud)
(固定链接到操场)
归档时间: |
|
查看次数: |
439 次 |
最近记录: |