vectorrustcollect

Rust collect() chunks of a vector into Vec<Vec<bool>>


I have a vector outputs of u64 which basically only has 0s and 1s. And I want to split the vector into equal parts to get a Vec<Vec<bool>> or Vec<&[bool]].

However, somehow I can't do it it tells me

256  |                     .collect();
     |                      ^^^^^^^ value of type `std::vec::Vec<std::vec::Vec<bool>>` cannot be built from `std::iter::Iterator<Item=bool>`

using

                let sqrt_output = (outputs.len() as f64).sqrt() as usize;
                let output_grid: Vec<&[bool]> = outputs
                    .chunks(sqrt_output)
                    .map(|s| {
                        match s {
                            [1_u64] => true,
                            [0_u64] => false,
                            // this is a hack but I don't know how to return an error ...
                            _ => true,
                        }
                    })
                    .collect();

Solution

  • To get back a Vec<Vec<bool>> your map closure would need to return a Vec<bool>

    Here's an example:

    fn main() {
        let outputs: Vec<u64> = vec![0, 1, 1, 0];
        let output_grid: Vec<Vec<bool>> = outputs
            .chunks(2)
            .map(|s| {  // this is an &[u64]
                let mut inner_vec = Vec::new();
                for val in s {
                    inner_vec.push(match val {
                        1 => true,
                        0 => false,
                        _ => panic!("illegal number") // can just avoid push-ing if you want to ignore other numbers
                    })
                }
                inner_vec
            })
            .collect();
        // this prints "[[false, true], [true, false]]"
        println!("{:?}", output_grid)
    }