3 ms·
Your example indeed perfectly demonstrates the subtlety of closures in Rust. Now let's imagine I want to return a nested closure, e.g., `impl Fn(i32) -> impl Fn
by Hirrolot 4y ago
Your example indeed perfectly demonstrates the subtlety of closures in Rust. Now let's imagine I want to return a nested closure, e.g., `impl Fn(i32) -> impl Fn(i32) -> i32`, or something like that:
fn adder(x: i32) -> impl Fn(i32) -> impl Fn(i32) -> i32 {
move |y| move |z| y + x + z
}
Alright, I can't. I can do that for a single closure, but can't for two or more of them. Here's why we have `#![feature(impl_trait_in_fn_trait_return)]` -- in Nightly, among many other such features.
- burntsushi 4y agoMy example didn't demonstrate the subtlety here, but it inspired your example, which of course does demonstrate some subtlety. And as I acknowledged in another comment, I of course agree there are subtleties to closures in Rust! And I agree there are useful nightly features that unlock additional use cases. Rust gives you enough rope to hang yourself with. For example, if you're okay with a heap allocation (like I assume you might be in a language with "non-broken closures" lol), then you don't need nightly Rust: fn adder(x: i32) -> impl Fn(i32) -> Box<dyn Fn(i32) -> i32> { move |y| Box::new(move |z| y + x + z) } fn main() { let add23 = adder(2)(3); assert_eq!(10, add23(5)); assert_eq!(13, add23(8)); } It's almost like "fundamentally broken" (not just "broken" but "fundamentally broken") and "has subtlety" are two totally different things. What a fucking revelation.