From 4711ba7a272ddf0475b69aeb958d0e2fcbf5df7f Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Sat, 13 May 2017 14:07:06 +0200 Subject: [PATCH] flow_control/loop: add example about returning values with break This commit adds an example for the loop_break_value feature. --- examples/flow_control/loop/return/input.md | 6 ++++++ examples/flow_control/loop/return/return.rs | 13 +++++++++++++ examples/structure.json | 3 ++- 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 examples/flow_control/loop/return/input.md create mode 100644 examples/flow_control/loop/return/return.rs diff --git a/examples/flow_control/loop/return/input.md b/examples/flow_control/loop/return/input.md new file mode 100644 index 0000000000..54989239bf --- /dev/null +++ b/examples/flow_control/loop/return/input.md @@ -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} diff --git a/examples/flow_control/loop/return/return.rs b/examples/flow_control/loop/return/return.rs new file mode 100644 index 0000000000..41810b0999 --- /dev/null +++ b/examples/flow_control/loop/return/return.rs @@ -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); +} diff --git a/examples/structure.json b/examples/structure.json index 290107d6dd..dc3b305e55 100644 --- a/examples/structure.json +++ b/examples/structure.json @@ -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 },