FromIterator
FromIterator
可讓您透過 Iterator
建構集合。
fn main() { let primes = vec![2, 3, 5, 7]; let prime_squares = primes.into_iter().map(|p| p * p).collect::<Vec<_>>(); println!("prime_squares: {prime_squares:?}"); }
This slide should take about 5 minutes.
Iterator
implements
fn collect<B>(self) -> B
where
B: FromIterator<Self::Item>,
Self: Sized
您可以透過兩種方式為這個方法指定 B
:
- 依指示使用「turbofish」:
some_iterator.collect::<COLLECTION_TYPE>()
。在這裡使用_
簡寫,可讓 Rust 推論Vec
元素的型別。 - 使用型別推論:
let prime_squares: Vec<_> = some_iterator.collect()
。請重新編寫這個例子,採用這個形式。
There are basic implementations of FromIterator
for Vec
, HashMap
, etc. There are also more specialized implementations which let you do cool things like convert an Iterator<Item = Result<V, E>>
into a Result<Vec<V>, E>
.