Rollup merge of #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 :) 💖
This commit is contained in:
Manish Goregaokar 2015-06-04 10:07:02 +05:30
commit 8b57130e84
2 changed files with 31 additions and 2 deletions

View File

@ -223,7 +223,9 @@
//! }
//! ```
//!
//! `try!` is imported by the prelude, and is available everywhere.
//! `try!` is imported by the prelude and is available everywhere, but it can only
//! be used in functions that return `Result` because of the early return of
//! `Err` that it provides.
#![stable(feature = "rust1", since = "1.0.0")]

View File

@ -117,7 +117,34 @@ macro_rules! println {
}
/// Helper macro for unwrapping `Result` values while returning early with an
/// error if the value of the expression is `Err`.
/// error if the value of the expression is `Err`. Can only be used in
/// functions that return `Result` because of the early return of `Err` that
/// it provides.
///
/// # Examples
///
/// ```
/// use std::io;
/// use std::fs::File;
/// use std::io::prelude::*;
///
/// fn write_to_file_using_try() -> Result<(), io::Error> {
/// let mut file = try!(File::create("my_best_friends.txt"));
/// try!(file.write_all(b"This is a list of my best friends."));
/// println!("I wrote to the file");
/// Ok(())
/// }
/// // This is equivalent to:
/// fn write_to_file_using_match() -> Result<(), io::Error> {
/// let mut file = try!(File::create("my_best_friends.txt"));
/// match file.write_all(b"This is a list of my best friends.") {
/// Ok(_) => (),
/// Err(e) => return Err(e),
/// }
/// println!("I wrote to the file");
/// Ok(())
/// }
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! try {