Skip to content

Commit

Permalink
Merge pull request #1865 from leon-matthews/fromstr-example
Browse files Browse the repository at this point in the history
Add an example of implementing the FromStr trait for Circles.
  • Loading branch information
marioidival authored Jul 16, 2024
2 parents 89aecb6 + 39bf14f commit 76ea853
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions src/conversion/string.md
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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<Self, Self::Err> {
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
Expand Down

0 comments on commit 76ea853

Please sign in to comment.