【问题标题】:Rust append a closure to a vectorRust 将闭包附加到向量
【发布时间】:2020-08-22 00:52:02
【问题描述】:

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

【问题讨论】:

    标签: types rust closures


    【解决方案1】:

    rust 中的方法名称与语言中的不同。您似乎有正确的想法,但Vec::append 函数将另一个向量的元素添加到目标实例中。

    你应该使用的方法是Vec::push,它将一个元素推到向量的后面。

    您可以从错误中看到,它希望您提供&amp;mut std::vec::Vec&lt;std::boxed::Box&lt;...&gt;&gt;,但收到了std::boxed::Box&lt;...&gt;

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

    【讨论】:

    • @Kryptomatrix 不用担心!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    相关资源
    最近更新 更多