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

帅比萌擦擦* 提交于 2019-12-03 23:33:42

问题


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]

回答1:


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



回答2:


cute is a macro for Python-esque list and dictionary (HashMap) comprehensions in Rust.

#[macro_use(c)]
extern crate cute;

let vector = c![x, for x in 1..10, if x % 2 == 0];


来源:https://stackoverflow.com/questions/45282970/does-rust-have-an-equivalent-to-pythons-list-comprehension-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!