Skip to content

Commit 76ea853

Browse files
authored
Merge pull request #1865 from leon-matthews/fromstr-example
Add an example of implementing the FromStr trait for Circles.
2 parents 89aecb6 + 39bf14f commit 76ea853

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

src/conversion/string.md

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,7 @@ shown in the following example.
3636

3737
This will convert the string into the type specified as long as the [`FromStr`]
3838
trait is implemented for that type. This is implemented for numerous types
39-
within the standard library. To obtain this functionality on a user defined type
40-
simply implement the [`FromStr`] trait for that type.
39+
within the standard library.
4140

4241
```rust,editable
4342
fn main() {
@@ -49,6 +48,35 @@ fn main() {
4948
}
5049
```
5150

51+
To obtain this functionality on a user defined type simply implement the
52+
[`FromStr`] trait for that type.
53+
54+
```rust,editable
55+
use std::num::ParseIntError;
56+
use std::str::FromStr;
57+
58+
#[derive(Debug)]
59+
struct Circle {
60+
radius: i32,
61+
}
62+
63+
impl FromStr for Circle {
64+
type Err = ParseIntError;
65+
fn from_str(s: &str) -> Result<Self, Self::Err> {
66+
match s.trim().parse() {
67+
Ok(num) => Ok(Circle{ radius: num }),
68+
Err(e) => Err(e),
69+
}
70+
}
71+
}
72+
73+
fn main() {
74+
let radius = " 3 ";
75+
let circle: Circle = radius.parse().unwrap();
76+
println!("{:?}", circle);
77+
}
78+
```
79+
5280
[`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html
5381
[Display]: https://doc.rust-lang.org/std/fmt/trait.Display.html
5482
[print]: ../hello/print.md

0 commit comments

Comments
 (0)