str::parse and Result
fn parse<F: FromStr>(&self) -> Result<F, F::Err>
enum Result<T, E> {
Ok(T),
Err(E),
}Parse text into a typed value and handle Ok and Err explicitly. A failed parse stays a Result; it does not become a silent default.
| Parameter | Description |
|---|---|
self | The input string. parse is a method on str, also available on String through deref. |
F | The target type, written with a turbofish such as parse::<u16>(). |
Returns: Ok(value) when the text is valid for F, otherwise Err with a type-specific error such as std::num::ParseIntError.
- This example is the original Rust reference recipe; the section id is unchanged.
- 65536 does not fit in a u16, so it is Err even though it is numeric. The next section shows the error text and an extra application check.
fn main() {
for input in ["8080", "65536", "oops"] {
match input.parse::<u16>() {
Ok(port) => println!("port: {port}"),
Err(_) => println!("invalid: {input}"),
}
}
}Expected output
port: 8080
invalid: 65536
invalid: oopsRelated: Original recipe on the Rust overview, Result