Skip to content

Commit d8ea10c

Browse files
Document the return keyword
Apply suggestions from code review Co-authored-by: Josh Triplett <josh@joshtriplett.org>
1 parent dcd470f commit d8ea10c

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

Diff for: src/libstd/keyword_docs.rs

+48-2
Original file line numberDiff line numberDiff line change
@@ -1000,9 +1000,55 @@ mod ref_keyword {}
10001000
//
10011001
/// Return a value from a function.
10021002
///
1003-
/// The documentation for this keyword is [not yet complete]. Pull requests welcome!
1003+
/// A `return` marks the end of an execution path in a function:
10041004
///
1005-
/// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1005+
/// ```
1006+
/// fn foo() -> i32 {
1007+
/// return 3;
1008+
/// }
1009+
/// assert_eq!(foo(), 3);
1010+
/// ```
1011+
///
1012+
/// `return` is not needed when the returned value is the last expression in the
1013+
/// function. In this case the `;` is omitted:
1014+
///
1015+
/// ```
1016+
/// fn foo() -> i32 {
1017+
/// 3
1018+
/// }
1019+
/// assert_eq!(foo(), 3);
1020+
/// ```
1021+
///
1022+
/// `return` returns from the function immediately (an "early return"):
1023+
///
1024+
/// ```no_run
1025+
/// use std::fs::File;
1026+
/// use std::io::{Error, ErrorKind, Read, Result};
1027+
///
1028+
/// fn main() -> Result<()> {
1029+
/// let mut file = match File::open("foo.txt") {
1030+
/// Ok(f) => f,
1031+
/// Err(e) => return Err(e),
1032+
/// };
1033+
///
1034+
/// let mut contents = String::new();
1035+
/// let size = match file.read_to_string(&mut contents) {
1036+
/// Ok(s) => s,
1037+
/// Err(e) => return Err(e),
1038+
/// };
1039+
///
1040+
/// if contents.contains("impossible!") {
1041+
/// return Err(Error::new(ErrorKind::Other, "oh no!"));
1042+
/// }
1043+
///
1044+
/// if size > 9000 {
1045+
/// return Err(Error::new(ErrorKind::Other, "over 9000!"));
1046+
/// }
1047+
///
1048+
/// assert_eq!(contents, "Hello, world!");
1049+
/// Ok(())
1050+
/// }
1051+
/// ```
10061052
mod return_keyword {}
10071053

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

0 commit comments

Comments
 (0)