gpt4 book ai didi

types - Rust将闭包附加到向量

转载 作者:行者123 更新时间:2023-12-03 11:32:36 25 4
gpt4 key购买 nike

正如this post所说,您可以创建一个闭包向量,如下所示:

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]>`

关于types - Rust将闭包附加到向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63531593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com