Skip to content

Commit 1a885f6

Browse files
committed
manual: add section on lambda expressions.
1 parent 2bb141c commit 1a885f6

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

doc/rust.md

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1975,13 +1975,47 @@ An example of a call expression:
19751975
let x: int = add(1, 2);
19761976
~~~~
19771977

1978-
### Shared function expressions
1978+
### Lambda expressions
19791979

1980-
*TODO*.
1980+
~~~~~~~~ {.abnf .gram}
1981+
ident_list : [ ident [ ',' ident ]* ] ? ;
1982+
lambda_expr : '|' ident_list '| expr ;
1983+
~~~~~~~~
19811984

1982-
### Unique function expressions
1985+
A _lambda expression_ (a.k.a. "anonymous function expression") defines a function and denotes it as a value,
1986+
in a single expression.
1987+
Lambda expressions are written by prepending a list of identifiers, surrounded by pipe symbols (`|`),
1988+
to an expression.
19831989

1984-
*TODO*.
1990+
A lambda expression denotes a function mapping parameters to the expression to the right of the `ident_list`.
1991+
The identifiers in the `ident_list` are the parameters to the function, with types inferred from context.
1992+
1993+
Lambda expressions are most useful when passing functions as arguments to other functions,
1994+
as an abbreviation for defining and capturing a separate fucntion.
1995+
1996+
Significantly, lambda expressions _capture their environment_,
1997+
which regular [function definitions](#functions) do not.
1998+
1999+
The exact type of capture depends on the [function type](#function-types) inferred for the lambda expression;
2000+
in the simplest and least-expensive form, the environment is captured by reference,
2001+
effectively borrowing pointers to all outer variables referenced inside the function.
2002+
Other forms of capture include making copies of captured variables,
2003+
and moving values from the environment into the lambda expression's captured environment.
2004+
2005+
An example of a lambda expression:
2006+
2007+
~~~~
2008+
fn ten_times(f: fn(int)) {
2009+
let mut i = 0;
2010+
while i < 10 {
2011+
f(i);
2012+
i += 1;
2013+
}
2014+
}
2015+
2016+
ten_times(|j| io::println(fmt!("hello, %d", j)));
2017+
2018+
~~~~
19852019

19862020
### While loops
19872021

0 commit comments

Comments
 (0)