Skip to content

Commit

Permalink
Merge pull request #867 from pietroalbini/loop_break_value
Browse files Browse the repository at this point in the history
Add an example about returning values with break
  • Loading branch information
steveklabnik authored Jul 24, 2017
2 parents 7760183 + 4711ba7 commit 201ad85
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
6 changes: 6 additions & 0 deletions examples/flow_control/loop/return/input.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
One of the uses of a `loop` is to retry an operation until it succeded. If the
operation returns a value though, you might need to pass it to the rest of the
code: put it after the `break`, and it will be returned by the `loop`
expression.

{return.play}
13 changes: 13 additions & 0 deletions examples/flow_control/loop/return/return.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
fn main() {
let mut counter = 0;

let result = loop {
counter += 1;

if counter == 10 {
break counter * 2;
}
};

assert_eq!(result, 20);
}
3 changes: 2 additions & 1 deletion examples/structure.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
{ "id": "flow_control", "title": "Flow Control", "children": [
{ "id": "if_else", "title": "if/else", "children": null },
{ "id": "loop", "title": "loop", "children": [
{ "id": "nested", "title": "Nesting and labels", "children": null }
{ "id": "nested", "title": "Nesting and labels", "children": null },
{ "id": "return", "title": "Returning from loops", "children": null }
] },
{ "id": "while", "title": "while", "children": null },
{ "id": "for", "title": "for and range", "children": null },
Expand Down

0 comments on commit 201ad85

Please sign in to comment.