result.rs - source
Skip to main content core/ result.rs 1 //! Error handling with the `Result` type. 2 //! 3 //! [`Result<T, E>`][`Result`] is the type used for returning and propagating 4 //! errors. It is an enum with the variants, [`Ok(T)`], representing 5 //! success and containing a value, and [`Err(E)`], representing error 6 //! and containing an error value. 7 //! 8 //! ``` 9 //! # #[allow(dead_code)] 10 //! enum Result<T, E> { 11 //!
Ok(T), 12 //! Err(E), 13 //! } 14 //! ``` 15 //! 16 //! Functions return [`Result`] whenever errors are expected and 17 //! recoverable. In the `std` crate, [`Result`] is most prominently used 18 //! for [I/O](../../std/io/index.html). 19 //! 20 //! A simple function returning [`Result`] might be 21 //! defined and used like so: 22 //! 23 //! ``` 24 //! #[derive(Debug)] 25 //! enum Version { Version1, Version2 } 26 //!
27 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> { 28 //! match header.get(0) { 29 //! None => Err("invalid header length"), 30 //! Some(&1) => Ok(Version::Version1), 31 //! Some(&2) => Ok(Version::Version2), 32 //! Some(_) => Err("invalid version"), 33 //! } 34 //! } 35 //! 36 //! let version = parse_version(&[1, 2, 3, 4]); 37 //! match version { 38 //! Ok(v) => println!("working with version: {v:?}"), 39 //!
Err(e) => println!("error parsing header: {e:?}"), 40 //! } 41 //! ``` 42 //! 43 //! Pattern matching on [`Result`]s is clear and straightforward for 44 //! simple cases, but [`Result`] comes with some convenience methods 45 //! that make working with it more succinct. 46 //! 47 //! ``` 48 //! // The `is_ok` and `is_err` methods do what they say. 49 //! let good_result: Result<i32, i32> = Ok(10); 50 //! let bad_result: Result<i32, i32> = Err(10); 51 //! assert!(good_result.is_ok() && !good_result.is_err()); 52 //! assert!(bad_result.is_err() && !bad_result.is_ok()); 53 //!
54 //! // `map` and `map_err` consume the `Result` and produce another. 55 //! let good_result: Result<i32, i32> = good_result.map(|i| i + 1); 56 //! let bad_result: Result<i32, i32> = bad_result.map_err(|i| i - 1); 57 //! assert_eq!(good_result, Ok(11)); 58 //! assert_eq!(bad_result, Err(9)); 59 //! 60 //! // Use `and_then` to continue the computation. 61 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11)); 62 //! assert_eq!(good_result, Ok(true)); 63 //!
64 //! // Use `or_else` to handle the error. 65 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20)); 66 //! assert_eq!(bad_result, Ok(29)); 67 //! 68 //! // Consume the result and return the contents with `unwrap`. 69 //! let final_awesome_result = good_result.unwrap(); 70 //! assert!(final_awesome_result) 71 //! ``` 72 //! 73 //! # Results must be used 74 //! 75 //! A common problem with using return values to indicate errors is 76 //! that it is easy to ignore the return value, thus failing to handle 77 //! the error. [`Result`] is annotated with the `#[must_use]` attribute, 78 //! which will cause the compiler to issue a warning when a Result 79 //! value is ignored.
This makes [`Result`] especially useful with 80 //! functions that may encounter errors but don't otherwise return a 81 //! useful value. 82 //! 83 //! Consider the [`write_all`] method defined for I/O types 84 //! by the [`Write`] trait: 85 //! 86 //! ``` 87 //! use std::io; 88 //! 89 //! trait Write { 90 //! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>; 91 //! } 92 //! ``` 93 //! 94 //! *Note: The actual definition of [`Write`] uses [`io::Result`], which 95 //! is just a synonym for <code>[Result]<T, [io::Error]></code>.* 96 //!
97 //! This method doesn't produce a value, but the write may 98 //! fail. It's crucial to handle the error case, and *not* write 99 //! something like this: 100 //! 101 //! ```no_run 102 //! # #![allow(unused_must_use)] // \o/ 103 //! use std::fs::File; 104 //! use std::io::prelude::*; 105 //! 106 //! let mut file = File::create("valuable_data.txt").unwrap(); 107 //! // If `write_all` errors, then we'll never know, because the return 108 //! // value is ignored.
109 //! file.write_all(b"important message"); 110 //! ``` 111 //! 112 //! If you *do* write that in Rust, the compiler will give you a 113 //! warning (by default, controlled by the `unused_must_use` lint). 114 //! 115 //! You might instead, if you don't want to handle the error, simply 116 //! assert success with [`expect`]. This will panic if the 117 //! write fails, providing a message explaining why the write was expected 118 //! to succeed: 119 //!
120 //! ```no_run 121 //! use std::fs::File; 122 //! use std::io::prelude::*; 123 //! 124 //! let mut file = File::create("valuable_data.txt").unwrap(); 125 //! file.write_all(b"important message").expect("writing to the file should succeed"); 126 //! ``` 127 //! 128 //! You might also simply assert success: 129 //! 130 //! ```no_run 131 //! # use std::fs::File; 132 //! # use std::io::prelude::*; 133 //! # let mut file = File::create("valuable_data.txt").unwrap(); 134 //! assert!(file.write_all(b"important message").is_ok()); 135 //! ``` 136 //!
137 //! Or propagate the error up the call stack with [`?`]: 138 //! 139 //! ``` 140 //! # use std::fs::File; 141 //! # use std::io::prelude::*; 142 //! # use std::io; 143 //! # #[allow(dead_code)] 144 //! fn write_message() -> io::Result<()> { 145 //! let mut file = File::create("valuable_data.txt")?; 146 //! file.write_all(b"important message")?; 147 //! Ok(()) 148 //! } 149 //! ``` 150 //! 151 //! # The question mark operator, `?` 152 //!
153 //! When writing code that calls many functions that return the 154 //! [`Result`] type, the error handling can be tedious. The question mark 155 //! operator, [`?`], hides some of the boilerplate of propagating errors 156 //! up the call stack. 157 //! 158 //! It replaces this: 159 //! 160 //! ``` 161 //! # #![allow(dead_code)] 162 //! use std::fs::File; 163 //! use std::io::prelude::*; 164 //! use std::io; 165 //!
166 //! struct Info { 167 //! name: String, 168 //! age: i32, 169 //! rating: i32, 170 //! } 171 //! 172 //! fn write_info(info: &Info) -> io::Result<()> { 173 //! // Early return on error 174 //! let mut file = match File::create("my_best_friends.txt") { 175 //! Err(e) => return Err(e), 176 //! Ok(f) => f, 177 //! }; 178 //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) { 179 //! return Err(e) 180 //! } 181 //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) { 182 //! return Err(e) 183 //! } 184 //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) { 185 //! return Err(e) 186 //! } 187 //!
Ok(()) 188 //! } 189 //! ``` 190 //! 191 //! With this: 192 //! 193 //! ``` 194 //! # #![allow(dead_code)] 195 //! use std::fs::File; 196 //! use std::io::prelude::*; 197 //! use std::io; 198 //! 199 //! struct Info { 200 //! name: String, 201 //! age: i32, 202 //! rating: i32, 203 //! } 204 //! 205 //! fn write_info(info: &Info) -> io::Result<()> { 206 //! let mut file = File::create("my_best_friends.txt")?; 207 //! // Early return on error 208 //! file.write_all(format!("name: {}\n", info.name).as_bytes())?; 209 //! file.write_all(format!("age: {}\n", info.age).as_bytes())?; 210 //! file.write_all(format!("rating: {}\n", info.rating).as_bytes())?; 211 //!
Ok(()) 212 //! } 213 //! ``` 214 //! 215 //! *It's much nicer!* 216 //! 217 //! Ending the expression with [`?`] will result in the [`Ok`]'s unwrapped value, unless the result 218 //! is [`Err`], in which case [`Err`] is returned early from the enclosing function. 219 //! 220 //! [`?`] can be used in functions that return [`Result`] because of the 221 //! early return of [`Err`] that it provides. 222 //! 223 //! [`expect`]: Result::expect 224 //! [`Write`]: ../../std/io/trait.Write.html "io::Write" 225 //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all "io::Write::write_all" 226 //! [`io::Result`]: ../../std/io/type.Result.html "io::Result" 227 //! [`?`]: crate::ops::
The rest of this page is on the live site.