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]
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]
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]
}
cute is a macro for Python-esque list and dictionary (HashMap
) comprehensions in Rust.
use cute::c;
let vector = c![x, for x in 1..10, if x % 2 == 0];
For anyone else looking for a python-like list\dict comprehension:
Python:
even_squares = [x for x in range(1, 10) if x % 2 == 0]
Rust equivalent:
let even_squares = comp![x for x in (1..10) if x % 2 == 0]
In cargo.toml:
list_comprehension_macro = "*"
Then:
use list_comprehension_macro::comp;
fn main() {
let arr: Vec<u32> = vec![1, 2, 3, 4];
let result = comp![x * 2 for x in arr];
}
Since rust 2018, you can do:
use cute::c;
…
let vector = c![x, for x in 1..10, if x % 2 == 0];
see https://doc.rust-lang.org/edition-guide/rust-2018/path-changes.html for why.