Skip to content

Updated "while let" example. #30059

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 29, 2015
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/doc/book/if-let.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ if let Some(x) = option {
## `while let`

In a similar fashion, `while let` can be used when you want to conditionally
loop as long as a value matches a certain pattern. It turns code like this:
loop as long as a value matches a certain pattern. It turns code like this:

```rust
# let option: Option<i32> = None;
Expand All @@ -73,8 +73,9 @@ loop {
Into code like this:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"no sugar" version of the while let over v.pop() looks like

let mut v = vec![1, 3, 5, 7, 11];
loop {
    match v.pop() {
        Some(x) =>  println!("{}", x),
        None => break,
    }
}


```rust
# let option: Option<i32> = None;
while let Some(x) = option {
let v: vec![1, 3, 5, 7, 11, ];
let mut iter: v.iter();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should be =, not : on these two lines.

But, why not show off something else than iterators since that's a good while let speciality? For example looping over the result of v.pop().

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let mut v = vec![1, 3, 5, 7, 11];
while let Some(x) = v.pop() {
    println!("{}", x);
}

while let Some(x) = iter.next() {
println!("{}", x);
}
```
Expand Down