Skip to content

Commit 131e254

Browse files
authored
Rollup merge of rust-lang#73648 - poliorcetics:return-keyword, r=joshtriplett
Document the return keyword Partial fix of rust-lang#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
2 parents f91330a + d8ea10c commit 131e254

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

src/libstd/keyword_docs.rs

+48-2
Original file line numberDiff line numberDiff line change
@@ -1068,9 +1068,55 @@ mod ref_keyword {}
10681068
//
10691069
/// Return a value from a function.
10701070
///
1071-
/// The documentation for this keyword is [not yet complete]. Pull requests welcome!
1071+
/// A `return` marks the end of an execution path in a function:
10721072
///
1073-
/// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1073+
/// ```
1074+
/// fn foo() -> i32 {
1075+
/// return 3;
1076+
/// }
1077+
/// assert_eq!(foo(), 3);
1078+
/// ```
1079+
///
1080+
/// `return` is not needed when the returned value is the last expression in the
1081+
/// function. In this case the `;` is omitted:
1082+
///
1083+
/// ```
1084+
/// fn foo() -> i32 {
1085+
/// 3
1086+
/// }
1087+
/// assert_eq!(foo(), 3);
1088+
/// ```
1089+
///
1090+
/// `return` returns from the function immediately (an "early return"):
1091+
///
1092+
/// ```no_run
1093+
/// use std::fs::File;
1094+
/// use std::io::{Error, ErrorKind, Read, Result};
1095+
///
1096+
/// fn main() -> Result<()> {
1097+
/// let mut file = match File::open("foo.txt") {
1098+
/// Ok(f) => f,
1099+
/// Err(e) => return Err(e),
1100+
/// };
1101+
///
1102+
/// let mut contents = String::new();
1103+
/// let size = match file.read_to_string(&mut contents) {
1104+
/// Ok(s) => s,
1105+
/// Err(e) => return Err(e),
1106+
/// };
1107+
///
1108+
/// if contents.contains("impossible!") {
1109+
/// return Err(Error::new(ErrorKind::Other, "oh no!"));
1110+
/// }
1111+
///
1112+
/// if size > 9000 {
1113+
/// return Err(Error::new(ErrorKind::Other, "over 9000!"));
1114+
/// }
1115+
///
1116+
/// assert_eq!(contents, "Hello, world!");
1117+
/// Ok(())
1118+
/// }
1119+
/// ```
10741120
mod return_keyword {}
10751121

10761122
#[doc(keyword = "self")]

0 commit comments

Comments
 (0)