Rust 将闭包附加到 vector
Rust append a closure to a vector
正如 所说,您可以像这样创建一个闭包向量:
let mut xs: Vec<Box<dyn Fn((i32, i32)) -> (i32, i32)>> = vec![
Box::new(move |(x, y)| (y, x)),
Box::new(move |(x, y)| (1 - y, 1 - x)),
];
但是为什么你不能使用以下方式附加到它:
xs.append(Box::new(move |(x, y)| (2 - y, 2 - x)));
这引发了错误:
|
162 | xs.append(Box::new(move |(x, y)| (2 - y, 2 - x)));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected mutable reference, found struct `std::boxed::Box`
|
= note: expected mutable reference `&mut std::vec::Vec<std::boxed::Box<dyn std::ops::Fn((i32, i32)) -> (i32, i32)>>`
found struct `std::boxed::Box<[closure@src/lib.rs:162:22: 162:50]>`
Rust 中方法的名称与语言中的不同。您的想法似乎是正确的,但是 Vec::append
函数将另一个向量的元素添加到目标实例中。
您应该使用的方法是 Vec::push
,它将一个元素推到向量的后面。
您可以从错误中看到它期望您提供 &mut std::vec::Vec<std::boxed::Box<...>>
但收到了 std::boxed::Box<...>
note: expected mutable reference `&mut std::vec::Vec<std::boxed::Box<dyn std::ops::Fn((i32, i32)) -> (i32, i32)>>`
found struct `std::boxed::Box<[closure@src/lib.rs:162:22: 162:50]>`
正如
let mut xs: Vec<Box<dyn Fn((i32, i32)) -> (i32, i32)>> = vec![
Box::new(move |(x, y)| (y, x)),
Box::new(move |(x, y)| (1 - y, 1 - x)),
];
但是为什么你不能使用以下方式附加到它:
xs.append(Box::new(move |(x, y)| (2 - y, 2 - x)));
这引发了错误:
|
162 | xs.append(Box::new(move |(x, y)| (2 - y, 2 - x)));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected mutable reference, found struct `std::boxed::Box`
|
= note: expected mutable reference `&mut std::vec::Vec<std::boxed::Box<dyn std::ops::Fn((i32, i32)) -> (i32, i32)>>`
found struct `std::boxed::Box<[closure@src/lib.rs:162:22: 162:50]>`
Rust 中方法的名称与语言中的不同。您的想法似乎是正确的,但是 Vec::append
函数将另一个向量的元素添加到目标实例中。
您应该使用的方法是 Vec::push
,它将一个元素推到向量的后面。
您可以从错误中看到它期望您提供 &mut std::vec::Vec<std::boxed::Box<...>>
但收到了 std::boxed::Box<...>
note: expected mutable reference `&mut std::vec::Vec<std::boxed::Box<dyn std::ops::Fn((i32, i32)) -> (i32, i32)>>`
found struct `std::boxed::Box<[closure@src/lib.rs:162:22: 162:50]>`