about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorCarol Nichols <carol.nichols@gmail.com>2015-06-03 10:12:16 -0400
committerCarol Nichols <carol.nichols@gmail.com>2015-06-03 10:12:16 -0400
commit9634bcbd3d120e7a13b62bb47e882fc9ce6338cd (patch)
tree242e0ba071a808b321eedcf7aaa2e48521df15fb /src
parent5b56d73dc0e8b988f91c44fd9f9e40331451796b (diff)
downloadrust-9634bcbd3d120e7a13b62bb47e882fc9ce6338cd.tar.gz
rust-9634bcbd3d120e7a13b62bb47e882fc9ce6338cd.zip
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.
Diffstat (limited to 'src')
-rw-r--r--src/libcore/result.rs4
-rw-r--r--src/libstd/macros.rs28
2 files changed, 30 insertions, 2 deletions
diff --git a/src/libcore/result.rs b/src/libcore/result.rs
index e909946ece4..003c4b2b78c 100644
--- a/src/libcore/result.rs
+++ b/src/libcore/result.rs
@@ -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")]
 
diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs
index 32193b4089d..a7c18783025 100644
--- a/src/libstd/macros.rs
+++ b/src/libstd/macros.rs
@@ -117,7 +117,33 @@ 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;
+///
+/// fn write_to_file_using_try() -> Result<(), io::Error> {
+///     let mut file = try!(File::create("my_best_friends.txt"));
+///     try!(file.write_line("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_line("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 {