Answer#
Call .iter() on a collection and chain adapters; end the chain with a consumer such as sum, collect, count or find. Nothing runs until the consumer runs, as with LINQ's deferred execution. The program below does eight typical LINQ queries and compiled and ran with rustc 1.93.0.
| LINQ | Rust |
|---|---|
Where | filter |
Select | map |
Sum, Count | sum, count |
Any, All | any, all |
FirstOrDefault(pred) | find(pred) (returns Option) |
SelectMany | flat_map |
Take, Skip | take, skip |
Zip, index in Select((x, i) => ...) | zip, enumerate |
Distinct | collect into a HashSet |
OrderBy, OrderByDescending | sort_by on a Vec (not lazy) |
GroupBy | a HashMap with entry |
ToList, ToDictionary | collect::<Vec<_>>(), collect::<HashMap<_, _>>() |
use std::collections::{HashMap, HashSet};
#[derive(Debug, Clone)]
struct Order {
customer: &'static str,
total: f64,
paid: bool,
}
fn main() {
let orders = vec![
Order { customer: "ada", total: 30.0, paid: true },
Order { customer: "bo", total: 12.5, paid: false },
Order { customer: "ada", total: 7.5, paid: true },
Order { customer: "cy", total: 99.0, paid: true },
];
// orders.Where(o => o.Paid).Select(o => o.Total).Sum()
let paid: f64 = orders.iter().filter(|o| o.paid).map(|o| o.total).sum();
// orders.Any(o => !o.Paid) orders.All(o => o.Total > 0)
let unpaid = orders.iter().any(|o| !o.paid);
let positive = orders.iter().all(|o| o.total > 0.0);
// orders.OrderByDescending(o => o.Total).Take(2) (sorting needs a Vec)
let mut sorted = orders.clone();
sorted.sort_by(|a, b| b.total.total_cmp(&a.total));
let top: Vec<_> = sorted.iter().take(2).map(|o| o.customer).collect();
// orders.GroupBy(o => o.Customer).ToDictionary(g => g.Key, g => g.Sum(o => o.Total))
let mut by_customer: HashMap<&str, f64> = HashMap::new();
for o in &orders {
*by_customer.entry(o.customer).or_default() += o.total;
}
// orders.Select(o => o.Customer).Distinct().Count()
let distinct = orders.iter().map(|o| o.customer).collect::<HashSet<_>>().len();
// orders.FirstOrDefault(o => o.Total > 50)
let big = orders.iter().find(|o| o.total > 50.0).map(|o| o.customer);
let pairs: Vec<(usize, &str)> = orders.iter().map(|o| o.customer).enumerate().collect();
let letters: Vec<char> = orders.iter().flat_map(|o| o.customer.chars()).collect();
println!("{paid} {unpaid} {positive} {top:?} {distinct} {big:?}");
let mut totals: Vec<_> = by_customer.into_iter().collect();
totals.sort_by(|a, b| a.0.cmp(b.0));
println!("{totals:?} {} {}", pairs.len(), letters.len());
}136.5 true true ["cy", "ada"] 3 Some("cy")
[("ada", 37.5), ("bo", 12.5), ("cy", 99.0)] 4 10Common mistakes#
- Forgetting the consumer. An iterator chain that ends in
map(...)does nothing by itself. - Expecting
HashMapto keep insertion order. Sort the result, as above, when the order matters. - Using
sortonf64. Floats are not totally ordered; usesort_bywithtotal_cmp.
Related questions#
Are iterator chains slower than a for loop?#
In optimised builds they compile to the same kind of loop; measure with cargo build --release before assuming a difference.
Is there a crate with more operators?#
Yes, the itertools crate adds grouping, joining and windowing helpers.
Sources#
- The Rust Book, "Processing a Series of Items with Iterators": https://doc.rust-lang.org/book/ch13-02-iterators.html
- Standard library,
Iterator: https://doc.rust-lang.org/std/iter/trait.Iterator.html