1

As this post says, you can create a vector of closures like this:

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)),
];

But why can't you append to it using:

xs.append(Box::new(move |(x, y)| (2 - y, 2 - x)));

This raises the error:

    |
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]>`
Volker Weißmann
  • 554
  • 1
  • 6
  • 24

1 Answers1

5

The names for the methods in rust are different than in languages. You seem to have the right idea but Vec::append function adds the elements of another vector into the target instance.

The method you should use is Vec::push, which pushes an element to the back of the vector.

You can see from the error that it was expecting you to provide a &mut std::vec::Vec<std::boxed::Box<...>> but received a 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]>`
joshmeranda
  • 3,001
  • 2
  • 10
  • 24