File tree Expand file tree Collapse file tree 1 file changed +30
-2
lines changed
Expand file tree Collapse file tree 1 file changed +30
-2
lines changed Original file line number Diff line number Diff line change @@ -36,8 +36,7 @@ shown in the following example.
3636
3737This will convert the string into the type specified as long as the [ ` FromStr ` ]
3838trait 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
4342fn 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
You can’t perform that action at this time.
0 commit comments