3 ms·
A lambda is usually passed as a generic argument, because that's the only way to avoid virtual dispatch (and the only way to take a lambda by-value without allo
by eridius 12y ago
A lambda is usually passed as a generic argument, because that's the only way to avoid virtual dispatch (and the only way to take a lambda by-value without allocation), but you can also use trait objects if you want:
fn foo(x: &Fn(i32)) {
x(5);
}
fn main() {
foo(&|x| println!("x: {}", x));
}
Or you can use std::boxed::FnBox in order to take a Box<FnBox(i32)> but that's currently marked as unstable (it exists because you can't take Box<FnOnce(..)> as you can't move out of the box in order to call the lambda as it does not have a statically-known size, but if you're ok taking Fn or FnMut then you don't need it).