snippetrustCritical
How to use a map over vectors?
Viewed 0 times
howusevectorsovermap
Problem
Although vectors are best suited for procedural programming, I would like to use a
Why isn't there any such function in the standard library (and also in
map function on them. The following snippet works:fn map(u: &Vec, f: &Fn(&A) -> B) -> Vec {
let mut res: Vec = Vec::with_capacity(u.len());
for x in u.iter() {
res.push(f(x));
}
res
}
fn f(x: &i32) -> i32 {
*x + 1
}
fn main() {
let u = vec![1, 2, 3];
let v = map(&u, &f);
println!("{} {} {}", v[0], v[1], v[2]);
}Why isn't there any such function in the standard library (and also in
std::collections::LinkedList)? Is there another way to deal with it?Solution
Rust likes to be more general than that; mapping is done over iterators, rather than over solely vectors or slices.
A couple of demonstrations:
This way of working with iterators also means that you often won’t even need to create intermediate vectors where in other languages or with other techniques you would; this is more efficient and typically just as natural.
A couple of demonstrations:
let u = vec![1, 2, 3];
let v: Vec = u.iter().map(f).collect();
let u = vec![1, 2, 3];
let v = u.iter().map(|&x| x + 1).collect::>();
.collect() is probably the most magic part of it, and allows you to collect all the elements of the iterator into a large variety of different types, as shown by the implementors of FromIterator. For example, an iterator of Ts can be collected to Vec, of chars can be collected to a String, of (K, V) pairs to a HashMap, and so forth.This way of working with iterators also means that you often won’t even need to create intermediate vectors where in other languages or with other techniques you would; this is more efficient and typically just as natural.
Context
Stack Overflow Q#30026893, score: 203
Revisions (0)
No revisions yet.