Skip to content

Commit 8450dc8

Browse files
committed
auto merge of #6972 : artagnon/rust/bad-for-loop, r=bstrie
I noticed this while reading the tutorial. [1/2] adds tests to guard against regressions. [2/2] corrects the tutorial. Please let me know if you have a standard place to put tests: they seem to be all over the place currently.
2 parents 8f18ea8 + dd923e3 commit 8450dc8

File tree

3 files changed

+24
-7
lines changed

3 files changed

+24
-7
lines changed

doc/tutorial.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1613,18 +1613,19 @@ loop. Like `do`, `for` is a nice syntax for describing control flow
16131613
with closures. Additionally, within a `for` loop, `break`, `loop`,
16141614
and `return` work just as they do with `while` and `loop`.
16151615

1616-
Consider again our `each` function, this time improved to
1617-
break early when the iteratee returns `false`:
1616+
Consider again our `each` function, this time improved to return
1617+
immediately when the iteratee returns `false`:
16181618

16191619
~~~~
1620-
fn each(v: &[int], op: &fn(v: &int) -> bool) {
1620+
fn each(v: &[int], op: &fn(v: &int) -> bool) -> bool {
16211621
let mut n = 0;
16221622
while n < v.len() {
16231623
if !op(&v[n]) {
1624-
break;
1624+
return false;
16251625
}
16261626
n += 1;
16271627
}
1628+
return true;
16281629
}
16291630
~~~~
16301631

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
fn main() {
12+
fn quux(_: &fn(&int) -> bool) -> () { }
13+
for quux |_| { } //~ ERROR expected `for` closure to return
14+
// `bool`, but found `()`
15+
}

src/test/compile-fail/bad-for-loop.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
// except according to those terms.
1010

1111
fn main() {
12-
fn baz(_x: &fn(y: int) -> int) {}
13-
for baz |_e| { } //~ ERROR A `for` loop iterator should expect a closure that returns `bool`
14-
//~^ ERROR expected `for` closure to return `bool`
12+
fn quux(_: &fn(&int) -> int) -> bool { true }
13+
for quux |_| { } //~ ERROR A `for` loop iterator should expect a
14+
// closure that returns `bool`. This iterator
15+
// expects a closure that returns `int`.
1516
}

0 commit comments

Comments
 (0)