@@ -991,9 +991,49 @@ mod pub_keyword {}
991991//
992992/// Bind by reference during pattern matching.
993993///
994- /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
994+ /// `ref` annotates pattern bindings to make them borrow rather than move.
995+ /// It is **not** a part of the pattern as far as matching is concerned.
996+ ///
997+ /// By default, [`match`] statements consume all they can, which can sometimes
998+ /// be a problem, when you don't really need the value to be moved and owned:
999+ ///
1000+ /// ```compile_fail,E0382
1001+ /// let maybe_name = Some(String::from("Alice"));
1002+ /// // The variable 'maybe_name' is consumed here ...
1003+ /// match maybe_name {
1004+ /// Some(n) => println!("Hello, {}", n),
1005+ /// _ => println!("Hello, world"),
1006+ /// }
1007+ /// // ... and now unavailable.
1008+ /// println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
1009+ /// ```
9951010///
996- /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1011+ /// Using the `ref` keyword, the value is only borrowed, not moved, making
1012+ /// available for use after the [`match`] statement:
1013+ ///
1014+ /// ```
1015+ /// let maybe_name = Some(String::from("Alice"));
1016+ /// // Using `ref`, the value is borrowed, not moved ...
1017+ /// match maybe_name {
1018+ /// Some(ref n) => println!("Hello, {}", n),
1019+ /// _ => println!("Hello, world"),
1020+ /// }
1021+ /// // ... and it's available here !
1022+ /// println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
1023+ /// ```
1024+ ///
1025+ /// # `&` vs `ref`
1026+ ///
1027+ /// - `&` denotes that your pattern expects a reference to an object. Hence `&`
1028+ /// is a part of said pattern: `&Foo` matches different objects than `Foo` does.
1029+ ///
1030+ /// - `ref` indicates that you want a reference to an unpacked value. It is not
1031+ /// matched against: `Foo(ref foo)` matches the same objects as `Foo(foo)`.
1032+ ///
1033+ /// See also the [Reference] for more information.
1034+ ///
1035+ /// [`match`]: keyword.match.html
1036+ /// [Reference]: ../reference/patterns.html#identifier-patterns
9971037mod ref_keyword { }
9981038
9991039#[ doc( keyword = "return" ) ]
0 commit comments