@@ -183,8 +183,8 @@ mode for your favorite editor, let us know so that we can link to it.
183
183
Assuming you've programmed in any C-family language (C++, Java,
184
184
JavaScript, C#, or PHP), Rust will feel familiar. The main surface
185
185
difference to be aware of is that the bodies of ` if ` statements and of
186
- loops * have* to be wrapped in brackets. Single-statement, bracket-less
187
- bodies are not allowed.
186
+ ` while ` loops * have* to be wrapped in brackets. Single-statement,
187
+ bracket-less bodies are not allowed.
188
188
189
189
If the verbosity of that bothers you, consider the fact that this
190
190
allows you to omit the parentheses around the condition in ` if ` ,
690
690
} while any_cake_left();
691
691
~~~~
692
692
693
- For more involved iteration, such as going over the elements of a hash
694
- table , Rust uses higher-order functions. We'll come back to those in a
695
- moment.
693
+ For more involved iteration, such as going over the elements of a
694
+ collection , Rust uses higher-order functions. We'll come back to those
695
+ in a moment.
696
696
697
697
## Failure
698
698
@@ -952,6 +952,49 @@ for_rev([1, 2, 3]) {|n|
952
952
Note that, because ` for_rev() ` returns unit type, no semicolon is
953
953
needed when the final closure is pulled outside of the parentheses.
954
954
955
+ # For loops
956
+
957
+ To allow breaking out of loops, many iteration functions, such as
958
+ ` vec::each ` , take a function that returns a boolean, and can return
959
+ ` false ` to break off iteration.
960
+
961
+ ~~~~
962
+ vec::each([2, 4, 8, 5, 16]) {|n|
963
+ if n % 2 != 0 {
964
+ io::println("found odd number!");
965
+ false
966
+ } else { true }
967
+ }
968
+ ~~~~
969
+
970
+ You can see how that gets noisy. As a syntactic convenience, if the
971
+ call is preceded by the keyword ` for ` , the block will implicitly
972
+ return ` true ` , and ` break ` and ` cont ` can be used, much like in a
973
+ ` while ` loop, to explicitly return ` false ` or ` true ` .
974
+
975
+ ~~~~
976
+ for vec::each([2, 4, 8, 5, 16]) {|n|
977
+ if n % 2 != 0 {
978
+ io::println("found odd number!");
979
+ break;
980
+ }
981
+ }
982
+ ~~~~
983
+
984
+ As an added bonus, you can use the ` ret ` keyword, which is not
985
+ normally allowed in blocks, in a block that appears as the body of a
986
+ ` for ` loop — this will cause a return to happen from the outer
987
+ function, not just the loop body.
988
+
989
+ ~~~~
990
+ fn contains(v: [int], elt: int) -> bool {
991
+ for vec::each(v) {|x|
992
+ if (x == elt) { ret true; }
993
+ }
994
+ false
995
+ }
996
+ ~~~~
997
+
955
998
# Datatypes
956
999
957
1000
Rust datatypes are, by default, immutable. The core datatypes of Rust
0 commit comments