about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorSteve Klabnik <steve@steveklabnik.com>2015-04-20 21:15:54 -0400
committerSteve Klabnik <steve@steveklabnik.com>2015-04-20 21:15:54 -0400
commit1d082de2d9849cfcc667721570cd0a3e070f05d7 (patch)
treee0ee0e653aff47b75375d0daca62a1cc41d000c5 /src
parentd09a0cda3a2268c081311c7ddf262c104130c7d2 (diff)
parent570b250b8f04f5e32f9710b90eba2d566d2f4594 (diff)
downloadrust-1d082de2d9849cfcc667721570cd0a3e070f05d7.tar.gz
rust-1d082de2d9849cfcc667721570cd0a3e070f05d7.zip
Rollup merge of #24643 - steveklabnik:doc_if_let, r=jakub-
and while let
Diffstat (limited to 'src')
-rw-r--r--src/doc/trpl/if-let.md81
1 files changed, 80 insertions, 1 deletions
diff --git a/src/doc/trpl/if-let.md b/src/doc/trpl/if-let.md
index 9e010b020c1..7173303e3b1 100644
--- a/src/doc/trpl/if-let.md
+++ b/src/doc/trpl/if-let.md
@@ -1,3 +1,82 @@
 % if let
 
-COMING SOON
+`if let` allows you to combine `if` and `let` together to reduce the overhead
+of certain kinds of pattern matches.
+
+For example, let’s say we have some sort of `Option<T>`. We want to call a function
+on it if it’s `Some<T>`, but do nothing if it’s `None`. That looks like this:
+
+```rust
+# let option = Some(5);
+# fn foo(x: i32) { }
+match option {
+    Some(x) => { foo(x) },
+    None => {},
+}
+```
+
+We don’t have to use `match` here, for example, we could use `if`:
+
+```rust
+# let option = Some(5);
+# fn foo(x: i32) { }
+if option.is_some() {
+    let x = option.unwrap();
+    foo(x);
+}
+```
+
+Neither of these options is particularly appealing. We can use `if let` to
+do the same thing in a nicer way:
+
+```rust
+# let option = Some(5);
+# fn foo(x: i32) { }
+if let Some(x) = option {
+    foo(x);
+}
+```
+
+If a [pattern][patterns] matches successfully, it binds any appropriate parts of
+the value to the identifiers in the pattern, then evaluates the expression. If
+the pattern doesn’t match, nothing happens.
+
+If you’d rather to do something else when the pattern does not match, you can
+use `else`:
+
+```rust
+# let option = Some(5);
+# fn foo(x: i32) { }
+# fn bar() { }
+if let Some(x) = option {
+    foo(x);
+} else {
+    bar();
+}
+```
+
+## `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:
+
+```rust
+# let option: Option<i32> = None;
+loop {
+    match option {
+        Some(x) => println!("{}", x),
+	_ => break,
+    }
+}
+```
+
+Into code like this:
+
+```rust
+# let option: Option<i32> = None;
+while let Some(x) = option {
+    println!("{}", x);
+}
+```
+
+[patterns]: patterns.html