3 ms·
That's a distinction that does exist in Rust. A lambda can only be passed to a generic function argument, something that looks like this: fn some_function<
by Animats 12y ago
That's a distinction that does exist in Rust. A lambda can only be passed to a generic function argument, something that looks like this:
fn some_function<F>(some_closure: F)
On the other hand, you can write a nested function and pass it as a parameter to a non-generic function. It just can't make references that would make it a closure. That's because Rust closures are really a syntactic hack for traits.
(All this complexity may turn off C programmers, and their management, for things that really need to be in something safer than C. The people who participate in language discussions do understand this stuff, but they're not the ones writing embedded code. Rust could go the way of C++, where metaprogramming became The Beast that Ate the Language.)
- steveklabnik 12y agoYou can also pass a fn to a function that takes a closure. fn foo<T: FnOnce(i32)>(x: T) { x(5); } fn bar(_: i32) { println!("Bar"); } fn main() { foo(bar); }
- eridius 12y agoA 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).
- dbaupp 12y agoYou're taking about the distinction between named functions and anonymous one, whereas I believe eridius was talking about the distinction between anonymous functions with or without captures.