Rust collect()将向量的块收集到Vec〈Vec>中< bool>

xyhw6mcr  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(166)

我有一个u64的向量outputs,基本上只有0和1,我想把这个向量分成相等的部分,得到Vec<Vec<bool>>Vec<&[bool]]
然而,不知怎么的我做不到它告诉我

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

使用

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();
q8l4jmvw

q8l4jmvw1#

若要取回Vec<Vec<bool>>,您的map闭包需要返回Vec<bool>
下面是一个例子:

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)
}

相关问题