3 ms·
Not sure if there is any point in implementing map_on_vec using map, but this code fn map_on_vec(vec: &Vec<i32>, func: fn(i32) -> i32) -> Vec<i32> {
by sampo 9y ago
Not sure if there is any point in implementing map_on_vec using map, but this code
fn map_on_vec(vec: &Vec<i32>, func: fn(i32) -> i32) -> Vec<i32>
{
let mut new_vec = Vec::new();
for i in 0..vec.len() {
new_vec.push(func(vec[i]));
}
new_vec
}
doesn't need to be based on mut, push and for. Something like this works, too:
fn map_on_vec(vec: &Vec<i32>, func: fn(i32) -> i32) -> Vec<i32>
{
let new_vec: Vec<i32> = vec
.iter()
.map(|x| func(*x))
.collect();
new_vec
}
At least it runs a tiny bit faster, without all the pushing.
- vvanders 9y agoI'm also looking forward to the impl trait work where you can return partial iterators as well instead of the massive type signature that they are today.
- shepmaster 9y agoAnd getting into idiomatic Rust + a bit of code golf + a bit of showing-off: fn map_on_vec(vec: &[i32], func: F) where F: Fn(i32) -> i32, { vec.iter().map(|x| func(*x)).collect() } - There's no need for the temporary variable, can just return directly - The `vec` argument should be a `&[T]` not a `&Vec<T>` [discouraged] - The `func` argument shouldn't be a function pointer but instead take an unboxed, generic closure (no forced pointer indirection, can take a closure). You may even want to accept a `FnMut` to allow the closure to mutate itself. [discouraged]: https://stackoverflow.com/q/40006219/155423 https://stackoverflow.com/q/40006219/155423
- leshow 9y agoshep! you forgot map_on_vec's return type. Thanks for writing the comment though, I was just about to point out Fn