HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustCritical

Does Rust have an equivalent to Python's list comprehension syntax?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
havesyntaxequivalentdoeslistrustcomprehensionpython

Problem

Python list comprehension is really simple:

>>> l = [x for x in range(1, 10) if x % 2 == 0]
>>> [2, 4, 6, 8]


Does Rust have an equivalent syntax like:

let vector = vec![x for x in (1..10) if x % 2 == 0]
// [2, 4, 6, 8]

Solution

You can just use iterators:

fn main() {
    let v1 = (0u32..9).filter(|x| x % 2 == 0).map(|x| x.pow(2)).collect::>();
    let v2 = (1..10).filter(|x| x % 2 == 0).collect::>();

    println!("{:?}", v1); // [0, 4, 16, 36, 64]
    println!("{:?}", v2); // [2, 4, 6, 8]
}

Code Snippets

fn main() {
    let v1 = (0u32..9).filter(|x| x % 2 == 0).map(|x| x.pow(2)).collect::<Vec<_>>();
    let v2 = (1..10).filter(|x| x % 2 == 0).collect::<Vec<u32>>();

    println!("{:?}", v1); // [0, 4, 16, 36, 64]
    println!("{:?}", v2); // [2, 4, 6, 8]
}

Context

Stack Overflow Q#45282970, score: 100

Revisions (0)

No revisions yet.