diff options
| author | Manish Goregaokar <manishsmail@gmail.com> | 2020-06-25 18:00:20 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-06-25 18:00:20 -0700 |
| commit | 131e25401ca1b2b78d703c2eb5c5109d9664871e (patch) | |
| tree | 5be091502d34046a48634458a25484369b26f67d /src/libstd | |
| parent | f91330abfa4771fe924a178210d2998adc1b77f3 (diff) | |
| parent | d8ea10c95fb5cf1674666fe4eae10ed761e2bfaa (diff) | |
| download | rust-131e25401ca1b2b78d703c2eb5c5109d9664871e.tar.gz rust-131e25401ca1b2b78d703c2eb5c5109d9664871e.zip | |
Rollup merge of #73648 - poliorcetics:return-keyword, r=joshtriplett
Document the return keyword Partial fix of #34601. This documents the `return` keyword with two short example to explain it is not needed for the last expression in a function and a long example to show its use when interrupting a function execution early. I did not put a link to the reference since the only link I found was https://doc.rust-lang.org/stable/reference/expressions/return-expr.html#return-expressions. @rustbot modify labels: T-doc,C-enhancement
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/keyword_docs.rs | 50 |
1 files changed, 48 insertions, 2 deletions
diff --git a/src/libstd/keyword_docs.rs b/src/libstd/keyword_docs.rs index c6b0f657179..f987eb67ea5 100644 --- a/src/libstd/keyword_docs.rs +++ b/src/libstd/keyword_docs.rs @@ -1068,9 +1068,55 @@ mod ref_keyword {} // /// Return a value from a function. /// -/// The documentation for this keyword is [not yet complete]. Pull requests welcome! +/// A `return` marks the end of an execution path in a function: /// -/// [not yet complete]: https://github.com/rust-lang/rust/issues/34601 +/// ``` +/// fn foo() -> i32 { +/// return 3; +/// } +/// assert_eq!(foo(), 3); +/// ``` +/// +/// `return` is not needed when the returned value is the last expression in the +/// function. In this case the `;` is omitted: +/// +/// ``` +/// fn foo() -> i32 { +/// 3 +/// } +/// assert_eq!(foo(), 3); +/// ``` +/// +/// `return` returns from the function immediately (an "early return"): +/// +/// ```no_run +/// use std::fs::File; +/// use std::io::{Error, ErrorKind, Read, Result}; +/// +/// fn main() -> Result<()> { +/// let mut file = match File::open("foo.txt") { +/// Ok(f) => f, +/// Err(e) => return Err(e), +/// }; +/// +/// let mut contents = String::new(); +/// let size = match file.read_to_string(&mut contents) { +/// Ok(s) => s, +/// Err(e) => return Err(e), +/// }; +/// +/// if contents.contains("impossible!") { +/// return Err(Error::new(ErrorKind::Other, "oh no!")); +/// } +/// +/// if size > 9000 { +/// return Err(Error::new(ErrorKind::Other, "over 9000!")); +/// } +/// +/// assert_eq!(contents, "Hello, world!"); +/// Ok(()) +/// } +/// ``` mod return_keyword {} #[doc(keyword = "self")] |
