PageRenderTime 43ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/src/doc/trpl/while-loops.md

http://github.com/graydon/rust
Markdown | 93 lines | 64 code | 29 blank | 0 comment | 0 complexity | 48f97266d29d6790e2a6c69ac0900c5e MD5 | raw file
Possible License(s): 0BSD, Apache-2.0, MIT, AGPL-1.0
  1. % while loops
  2. Rust also has a `while` loop. It looks like this:
  3. ```{rust}
  4. let mut x = 5; // mut x: u32
  5. let mut done = false; // mut done: bool
  6. while !done {
  7. x += x - 3;
  8. println!("{}", x);
  9. if x % 5 == 0 {
  10. done = true;
  11. }
  12. }
  13. ```
  14. `while` loops are the correct choice when youre not sure how many times
  15. you need to loop.
  16. If you need an infinite loop, you may be tempted to write this:
  17. ```rust,ignore
  18. while true {
  19. ```
  20. However, Rust has a dedicated keyword, `loop`, to handle this case:
  21. ```rust,ignore
  22. loop {
  23. ```
  24. Rusts control-flow analysis treats this construct differently than a `while
  25. true`, since we know that it will always loop. In general, the more information
  26. we can give to the compiler, the better it can do with safety and code
  27. generation, so you should always prefer `loop` when you plan to loop
  28. infinitely.
  29. ## Ending iteration early
  30. Lets take a look at that `while` loop we had earlier:
  31. ```rust
  32. let mut x = 5;
  33. let mut done = false;
  34. while !done {
  35. x += x - 3;
  36. println!("{}", x);
  37. if x % 5 == 0 {
  38. done = true;
  39. }
  40. }
  41. ```
  42. We had to keep a dedicated `mut` boolean variable binding, `done`, to know
  43. when we should exit out of the loop. Rust has two keywords to help us with
  44. modifying iteration: `break` and `continue`.
  45. In this case, we can write the loop in a better way with `break`:
  46. ```rust
  47. let mut x = 5;
  48. loop {
  49. x += x - 3;
  50. println!("{}", x);
  51. if x % 5 == 0 { break; }
  52. }
  53. ```
  54. We now loop forever with `loop` and use `break` to break out early.
  55. `continue` is similar, but instead of ending the loop, goes to the next
  56. iteration. This will only print the odd numbers:
  57. ```rust
  58. for x in 0..10 {
  59. if x % 2 == 0 { continue; }
  60. println!("{}", x);
  61. }
  62. ```
  63. Both `continue` and `break` are valid in both `while` loops and [`for` loops][for].
  64. [for]: for-loops.html