Does Rust have equivalent Python list comprehension syntax?

Understanding the Python list is really simple:

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

Does Rust have the same syntax as:

 let vector = vec![x for x in (1..10) if x % 2 == 0] // [2, 4, 6, 8] 
+16
syntax list-comprehension rust iterable
source share
2 answers

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] } 
+24
source share

cute is a macro for Python-esque and vocabulary ( HashMap ) concepts in Rust.

 #[macro_use(c)] extern crate cute; let vector = c![x, for x in 1..10, if x % 2 == 0]; 
+21
source share

All Articles