3 ms·
And 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, {
by shepmaster 9y ago
And 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