From b8caa5c2a93993f67087a9cf41c91d9585e567e9 Mon Sep 17 00:00:00 2001 From: Jon <33984245+jon32446@users.noreply.github.com> Date: Fri, 11 Nov 2022 14:11:38 +0200 Subject: [PATCH] Clarify the confusing closure example #1611 --- src/fn/closures.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/fn/closures.md b/src/fn/closures.md index 0c1b999efd..82286003b6 100644 --- a/src/fn/closures.md +++ b/src/fn/closures.md @@ -19,21 +19,23 @@ Other characteristics of closures include: ```rust,editable fn main() { - // Increment via closures and functions. - fn function(i: i32) -> i32 { i + 1 } + let outer_var = 42; + + // A regular function can't refer to variables in the enclosing environment + //fn function(i: i32) -> i32 { i + outer_var } + // TODO: uncomment the line above and see the compiler error. The compiler + // suggests that we define a closure instead. // Closures are anonymous, here we are binding them to references // Annotation is identical to function annotation but is optional // as are the `{}` wrapping the body. These nameless functions // are assigned to appropriately named variables. - let closure_annotated = |i: i32| -> i32 { i + 1 }; - let closure_inferred = |i | i + 1 ; - - let i = 1; - // Call the function and closures. - println!("function: {}", function(i)); - println!("closure_annotated: {}", closure_annotated(i)); - println!("closure_inferred: {}", closure_inferred(i)); + let closure_annotated = |i: i32| -> i32 { i + outer_var }; + let closure_inferred = |i | i + outer_var ; + + // Call the closures. + println!("closure_annotated: {}", closure_annotated(1)); + println!("closure_inferred: {}", closure_inferred(1)); // Once closure's type has been inferred, it cannot be inferred again with another type. //println!("cannot reuse closure_inferred with another type: {}", closure_inferred(42i64)); // TODO: uncomment the line above and see the compiler error.