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.
36
36
37
37
This will convert the string into the type specified as long as the [ ` FromStr ` ]
38
38
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.
41
40
42
41
``` rust,editable
43
42
fn main() {
@@ -49,6 +48,35 @@ fn main() {
49
48
}
50
49
```
51
50
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
+
52
80
[ `ToString` ] : https://doc.rust-lang.org/std/string/trait.ToString.html
53
81
[ Display ] : https://doc.rust-lang.org/std/fmt/trait.Display.html
54
82
[ print ] : ../hello/print.md
You can’t perform that action at this time.
0 commit comments