Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

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

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]
question from:https://stackoverflow.com/questions/45282970/does-rust-have-an-equivalent-to-pythons-list-comprehension-syntax

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can just use iterators:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...