Rust collect
Created By: chatGPT
Collect is a method in Rust that transforms an iterator into a collection. It is commonly used with various collection types such as vectors, hashmaps, and sets. The collect() method takes ownership of the iterator and builds a collection from its items. Here are some examples to illustrate how it works.
let numbers = vec![1, 2, 3, 4];
let doubled: Vec<i32> = numbers.iter().map(|x| x * 2).collect();
// doubled is now Vec<i32> containing [2, 4, 6, 8]
You can also collect items into a
HashMap
. In this example, we will create a hashmap from two vectors: one for keys and another for values.use std::collections::HashMap;
let keys = vec!["one", "two", "three"];
let values = vec![1, 2, 3];
let hashmap: HashMap<_, _> = keys.into_iter().zip(values.into_iter()).collect();
// hashmap is now {'one': 1, 'two': 2, 'three': 3}
In addition to Vec and HashMap, you can collect into a Set as well. However, Rust does not have a built-in Set type, so we typically use the HashSet from the standard library. Here's how to collect items into a HashSet.
use std::collections::HashSet;
let numbers = vec![1, 2, 3, 1, 2];
let unique_numbers: HashSet<_> = numbers.into_iter().collect();
// unique_numbers contains {1, 2, 3}
It's important to note that you can only collect into a collection that implements the FromIterator trait. Each collection type in Rust has different ways to handle the items, but the collect() method unifies this behavior.
let chars: Vec<char> = "hello".chars().collect();
// chars now contains ['h', 'e', 'l', 'l', 'o']
Using collect() is efficient since it allocates memory for the collection based on the size of the items from the iterator. It can be especially useful when converting or transforming iterators into usable collections in Rust programming.
let squared: Vec<i32> = (1..=5).map(|x| x * x).collect();
// squared is now Vec<i32> containing [1, 4, 9, 16, 25]