Puzzle 20: Explanation
Explore how Rust closures differ from regular functions in shadowing and naming. Understand static and dynamic dispatch methods, including conditional compilation with feature flags and constant functions, to control program behavior at compile time or runtime.
Test it out
Hit “Run” to see the code’s output.
fn main() {
let hello = || println!("Hello World");
let hello = || println!("Bonjour le monde");
hello();
}Explanation
In Rust, we can’t shadow functions with identical names, even if the parameter list is different. Function shadowing rules do not apply to closures, which are sometimes also called
Closures don’t actually have names within code. The variable that holds a closure is simply a pointer marking the area of memory containing the function. The variables that point to the closures are subject to the same shadowing rules as other variables. Function name mangling doesn’t apply because closures don’t have function names to mangle. Instead, they’re identified by the variable that points to them.
We can create as many shadow lambda functions as we like. They’ll be subject to the same scoping rules as ...