Skip to content

Commit 45e62d0

Browse files
committed
tutorial: Discuss argument patterns
1 parent d098faa commit 45e62d0

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

doc/tutorial.md

+24
Original file line numberDiff line numberDiff line change
@@ -813,6 +813,15 @@ assert 8 == line(5, 3, 1);
813813
assert () == oops(5, 3, 1);
814814
~~~~
815815

816+
As with `match` expressions and `let` bindings, function arguments support
817+
pattern destructuring. Like `let`, argument patterns must be irrefutable,
818+
as in this example that unpacks a tuple and returns it.
819+
820+
~~~
821+
fn first((value, _): (int, float)) -> int { value }
822+
~~~
823+
824+
816825
# The Rust memory model
817826

818827
At this junction, let's take a detour to explain the concepts involved
@@ -1576,6 +1585,21 @@ fn contains(v: &[int], elt: int) -> bool {
15761585
}
15771586
~~~~
15781587

1588+
Notice that, because `each` passes each value by borrowed pointer,
1589+
the iteratee needs to dereference it before using.
1590+
In these situations it can be convenient to lean on Rust's
1591+
argument patterns to bind `x` to the actual value, not the pointer.
1592+
1593+
~~~~
1594+
# use each = vec::each;
1595+
# fn contains(v: &[int], elt: int) -> bool {
1596+
for each(v) |&x| {
1597+
if (x == elt) { return true; }
1598+
}
1599+
# false
1600+
# }
1601+
~~~~
1602+
15791603
`for` syntax only works with stack closures.
15801604

15811605
> ***Note:*** This is, essentially, a special loop protocol:

0 commit comments

Comments
 (0)