Skip to content

Commit 8b57130

Browse files
committed
Rollup merge of rust-lang#25990 - carols10cents:try-docs, r=nikomatsakis
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. I seriously had this epiphany a few days ago after working with Rust for MONTHS, and after seeing [a friend have to come to the same realization](http://joelmccracken.github.io/entries/a-simple-web-app-in-rust-pt-2a/), I'd like to save more people from this confusion :) 💖
2 parents 5421b1f + c692d75 commit 8b57130

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

src/libcore/result.rs

+3-1
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

+28-1
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,34 @@ 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+
/// use std::io::prelude::*;
130+
///
131+
/// fn write_to_file_using_try() -> Result<(), io::Error> {
132+
/// let mut file = try!(File::create("my_best_friends.txt"));
133+
/// try!(file.write_all(b"This is a list of my best friends."));
134+
/// println!("I wrote to the file");
135+
/// Ok(())
136+
/// }
137+
/// // This is equivalent to:
138+
/// fn write_to_file_using_match() -> Result<(), io::Error> {
139+
/// let mut file = try!(File::create("my_best_friends.txt"));
140+
/// match file.write_all(b"This is a list of my best friends.") {
141+
/// Ok(_) => (),
142+
/// Err(e) => return Err(e),
143+
/// }
144+
/// println!("I wrote to the file");
145+
/// Ok(())
146+
/// }
147+
/// ```
121148
#[macro_export]
122149
#[stable(feature = "rust1", since = "1.0.0")]
123150
macro_rules! try {

0 commit comments

Comments
 (0)