rust list comprehension

Rust List Comprehension

In Rust, list comprehension is not a built-in feature like in some other programming languages. However, you can achieve similar functionality using iterators and functional programming concepts.

One common approach is to use the map and filter methods provided by iterators to transform and filter elements in a collection. Here's an example of how you can use these methods to achieve list comprehension-like behavior in Rust:

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];

    let squares: Vec<_> = numbers.iter().map(|x| x * x).collect();
    println!("{:?}", squares);

    let even_numbers: Vec<_> = numbers.iter().filter(|x| x % 2 == 0).collect();
    println!("{:?}", even_numbers);
}

In the above code, the map method is used to square each element in the numbers vector, and the filter method is used to select only the even numbers. The results are collected into new vectors (squares and even_numbers, respectively) using the collect method.

This approach allows you to perform transformations and filtering on collections in a concise and expressive manner, similar to list comprehensions in other languages.

Please let me know if you need further assistance!