How to print elements of 2D vector

Given this 2D vector, I want to print its element, as one vector per row:

main(){

   let mut 2d_vec: Vec<Vec<f64>> = Vec::new();

   2d_vec = vec![
       vec![1.,2.,3.],
       vec![4.,5.,6.],
       vec![7.,8.,9.]
   ];

   2d_vec.into_iter().for_each(|it| {
            println!("{:#?}", it);
   })
}

I got the below error:

error[E0507]: cannot move out of `2d_vec`, a captured variable in an `FnMut` closure
  --> src/main.rs:75:9
   |
39 |     let mut 2d_vec: Vec<Vec<f64>> = Vec::new();
   |         ----------- captured outer variable
...
75 |         2d_vec.into_iter().for_each(|it| {
   |         ^^^^^^^ move occurs because `2d_vec` has type `std::vec::Vec<std::vec::Vec<f64>>`, which does not implement the `Copy` trait

error: aborting due to previous error

Not sure how you're getting this error, as all I did was change the name of 2d_vec into vec_2d and it compiled and ran as expected:

(BTW, you cannot start your variable names with an integer)

Also, into_iter consumes the value into a new one. Just use iter if you want a reference to the data instead without consuming vec_2d. This is probably why you got your error

fn main(){
   let mut vec_2d: Vec<Vec<f64>> = Vec::new();

   vec_2d = vec![
       vec![1.,2.,3.],
       vec![4.,5.,6.],
       vec![7.,8.,9.]
   ];

   vec_2d.iter().for_each(|it| {
            println!("{:#?}", it);
   })
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.