From e6f1a4db5fb98407e33bfe33b2bb3debd686047f Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Thu, 16 Apr 2015 15:50:24 -0400 Subject: [PATCH] remove example usage of from_str in error docs Fixes #24185 --- src/doc/trpl/error-handling.md | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/doc/trpl/error-handling.md b/src/doc/trpl/error-handling.md index 491f7b0c2a0f3..492514456ebe8 100644 --- a/src/doc/trpl/error-handling.md +++ b/src/doc/trpl/error-handling.md @@ -20,18 +20,18 @@ panic. A *failure* is an error that can be recovered from in some way. A *panic* is an error that cannot be recovered from. What do we mean by "recover"? Well, in most cases, the possibility of an error -is expected. For example, consider the `from_str` function: +is expected. For example, consider the `parse` function: -```{rust,ignore} -from_str("5"); +```ignore +"5".parse(); ``` -This function takes a string argument and converts it into another type. But -because it's a string, you can't be sure that the conversion actually works. -For example, what should this convert to? +This method converts a string into another type. But because it's a string, you +can't be sure that the conversion actually works. For example, what should this +convert to? -```{rust,ignore} -from_str("hello5world"); +```ignore +"hello5world".parse(); ``` This won't work. So we know that this function will only work properly for some @@ -40,7 +40,8 @@ inputs. It's expected behavior. We call this kind of error a *failure*. On the other hand, sometimes, there are errors that are unexpected, or which we cannot recover from. A classic example is an `assert!`: -```{rust,ignore} +```rust +# let x = 5; assert!(x == 5); ``` @@ -119,17 +120,19 @@ Rust calls these sorts of errors *panics*. # Handling errors with `Option` and `Result` The simplest way to indicate that a function may fail is to use the `Option` -type. Remember our `from_str()` example? Here's its type signature: +type. For example, the `find` method on strings attempts to find a pattern +in a string, and returns an `Option`: -```{rust,ignore} -pub fn from_str(s: &str) -> Option +```rust +let s = "foo"; + +assert_eq!(s.find('f'), Some(0)); +assert_eq!(s.find('z'), None); ``` -`from_str()` returns an `Option`. If the conversion succeeds, it will return -`Some(value)`, and if it fails, it will return `None`. This is appropriate for the simplest of cases, but doesn't give us a lot of -information in the failure case. What if we wanted to know _why_ the conversion +information in the failure case. What if we wanted to know _why_ the function failed? For this, we can use the `Result` type. It looks like this: ```rust