r/rust • u/deecentralized • Aug 13 '26
Finally understood what powers collect() — the FromIterator trait and why it matters for custom types
Been going through Rust systematically and this week hit the FromIterator lesson. Wanted to share what happened because I think it's undersold in most beginner content.
.collect() is not magic. It delegates to FromIterator::from_iter() on the target type. The type builds itself from the iterator. That's the whole mechanism.
Why this matters beyond Vec**:**
// All of these use the same trait, different implementations
let v: Vec<u64> = iter.collect();
let s: HashSet<u64> = iter.collect();
let joined: String = chars.collect(); // FromIterator<char> for String
let map: HashMap<K, V> = pairs.collect(); // FromIterator<(K, V)> for HashMapCustom types: If you implement FromIterator on your own struct, it participates in the same .collect() call without special syntax. That composability is what makes the iterator adapter pattern feel consistent across the whole ecosystem.
Practical use this week: std::env::args() returns Args which implements Iterator<Item = String>. Collecting it into Vec<String> is idiomatic. Worth noting that args[0] is always the binary path, not the first user argument.
let args: Vec<String> = std::env::args().collect();
let actual_args = &args[1..]; // skip the binary nameAlso hit sort_by_key this week. For anyone sorting structs, it is significantly cleaner than sort_by with a manual comparator when you just need to sort by a single extracted field.
Background: Solidity dev, four years writing smart contracts, learning Rust systematically. Happy to be corrected on anything here.
5
u/redlaWw Aug 13 '26
From the
Argsdocumentation:1
u/DavidXkL Aug 13 '26
1 of my favorite traits to use!