Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if length of all vectors is the same in Rust

Tags:

rust

Given a vector of vectors of some value T, ie. Vec<Vec<T>>.

What's the idiomatic way to check if the inner vectors have the same length? (without external dependencies)

That is, true if all the inner vectors have the same length, and false otherwise.

like image 350
kentwait Avatar asked Jan 27 '23 17:01

kentwait


1 Answers

You can use the all method to check if all elements of an iterator match a predicate. Then just compare against the first element in the list.

fn main() {
    let vec_of_vecs = vec![
        vec![1, 2, 3],
        vec![1, 2, 3],
        vec![1, 2, 3],
        vec![1, 2, 3],
        vec![1, 2, 3],
        vec![1, 2, 3, 4], // remove this to prove that it works for both cases
    ];
    let all_same_length = vec_of_vecs
        .iter()
        .all(|ref v| v.len() == vec_of_vecs[0].len());

    if all_same_length {
        println!("They're all the same");
    } else {
        println!("They are not the same");
    }
}
like image 57
Mike Cluck Avatar answered Feb 01 '23 11:02

Mike Cluck