mirror of
https://github.com/ahgamut/rust-ape-example.git
synced 2024-05-15 01:52:42 +00:00
35 lines
1.1 KiB
Rust
35 lines
1.1 KiB
Rust
// ./src/fn/closures.md
|
|
|
|
|
|
fn part0() {
|
|
// Increment via closures and functions.
|
|
fn function(i: i32) -> i32 { i + 1 }
|
|
|
|
// 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));
|
|
// 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.
|
|
|
|
// A closure taking no arguments which returns an `i32`.
|
|
// The return type is inferred.
|
|
let one = || 1;
|
|
println!("closure returning one: {}", one());
|
|
|
|
}
|
|
|
|
pub fn main() {
|
|
part0();
|
|
}
|
|
|