Skip to content

Commit 9634bcb

Browse files
committed
Improve try! docs to make clearer it returns Result.
The API documentation is not explicit enough that because `try!` returns `Err` early for you, you can only use it in functions that return `Result`. The book mentions this, but if you come across `try!` outside of the book and look it up in the docs, this restriction on the return type of the function is not particularly clear.
1 parent 5b56d73 commit 9634bcb

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/libcore/result.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,9 @@
223223
//! }
224224
//! ```
225225
//!
226-
//! `try!` is imported by the prelude, and is available everywhere.
226+
//! `try!` is imported by the prelude and is available everywhere, but it can only
227+
//! be used in functions that return `Result` because of the early return of
228+
//! `Err` that it provides.
227229
228230
#![stable(feature = "rust1", since = "1.0.0")]
229231

src/libstd/macros.rs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,33 @@ macro_rules! println {
117117
}
118118

119119
/// Helper macro for unwrapping `Result` values while returning early with an
120-
/// error if the value of the expression is `Err`.
120+
/// error if the value of the expression is `Err`. Can only be used in
121+
/// functions that return `Result` because of the early return of `Err` that
122+
/// it provides.
123+
///
124+
/// # Examples
125+
///
126+
/// ```
127+
/// use std::io;
128+
/// use std::fs::File;
129+
///
130+
/// fn write_to_file_using_try() -> Result<(), io::Error> {
131+
/// let mut file = try!(File::create("my_best_friends.txt"));
132+
/// try!(file.write_line("This is a list of my best friends."));
133+
/// println!("I wrote to the file");
134+
/// Ok()
135+
/// }
136+
/// // This is equivalent to:
137+
/// fn write_to_file_using_match() -> Result<(), io::Error> {
138+
/// let mut file = try!(File::create("my_best_friends.txt"));
139+
/// match file.write_line("This is a list of my best friends.") {
140+
/// Ok(_) => (),
141+
/// Err(e) => return Err(e),
142+
/// }
143+
/// println!("I wrote to the file");
144+
/// Ok()
145+
/// }
146+
/// ```
121147
#[macro_export]
122148
#[stable(feature = "rust1", since = "1.0.0")]
123149
macro_rules! try {

0 commit comments

Comments
 (0)