diff --git a/src/conversion/string.md b/src/conversion/string.md index d8ed4808ea..d6958d47ad 100644 --- a/src/conversion/string.md +++ b/src/conversion/string.md @@ -36,8 +36,7 @@ shown in the following example. This will convert the string into the type specified as long as the [`FromStr`] trait is implemented for that type. This is implemented for numerous types -within the standard library. To obtain this functionality on a user defined type -simply implement the [`FromStr`] trait for that type. +within the standard library. ```rust,editable fn main() { @@ -49,6 +48,35 @@ fn main() { } ``` +To obtain this functionality on a user defined type simply implement the +[`FromStr`] trait for that type. + +```rust,editable +use std::num::ParseIntError; +use std::str::FromStr; + +#[derive(Debug)] +struct Circle { + radius: i32, +} + +impl FromStr for Circle { + type Err = ParseIntError; + fn from_str(s: &str) -> Result { + match s.trim().parse() { + Ok(num) => Ok(Circle{ radius: num }), + Err(e) => Err(e), + } + } +} + +fn main() { + let radius = " 3 "; + let circle: Circle = radius.parse().unwrap(); + println!("{:?}", circle); +} +``` + [`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html [Display]: https://doc.rust-lang.org/std/fmt/trait.Display.html [print]: ../hello/print.md