@@ -55,3 +55,80 @@ fn main() {
55
55
println!("number of retries: {}", num_retries);
56
56
}
57
57
```
58
+
59
+ More complex types can be passed in as flags too as long as they implement ` FromStr ` and ` Clone ` traits. Example -
60
+
61
+ ```
62
+ extern crate flags;
63
+
64
+ use flags::{Flag, FlagSet};
65
+ use std::env;
66
+ use std::num::ParseIntError;
67
+ use std::process;
68
+ use std::str::FromStr;
69
+
70
+ #[derive(Debug, PartialEq)]
71
+ struct Point {
72
+ x: i32,
73
+ y: i32,
74
+ }
75
+
76
+ impl Clone for Point {
77
+ fn clone(&self) -> Self {
78
+ let x = self.x;
79
+ let y = self.y;
80
+ Self { x, y }
81
+ }
82
+ }
83
+
84
+ impl ToString for Point {
85
+ fn to_string(&self) -> String {
86
+ format!("({},{})", self.x, self.y)
87
+ }
88
+ }
89
+
90
+ impl FromStr for Point {
91
+ type Err = ParseIntError;
92
+
93
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
94
+ let (x, y) = s
95
+ .strip_prefix('(')
96
+ .and_then(|s| s.strip_suffix(')'))
97
+ .and_then(|s| s.split_once(','))
98
+ .unwrap();
99
+
100
+ let x_fromstr = x.parse::<i32>()?;
101
+ let y_fromstr = y.parse::<i32>()?;
102
+
103
+ Ok(Point {
104
+ x: x_fromstr,
105
+ y: y_fromstr,
106
+ })
107
+ }
108
+ }
109
+
110
+ fn main() {
111
+ let point_flag = Flag::new(
112
+ Some("-p"),
113
+ Some("--point"),
114
+ "point on the 2d plane",
115
+ true,
116
+ Flag::kind::<Point>(),
117
+ Some(Box::new(Point { x: 0, y: 0 })),
118
+ );
119
+
120
+ let mut flagset = FlagSet::new();
121
+ flagset.add(&point_flag);
122
+ let result = flagset.parse(&mut env::args());
123
+ match result {
124
+ Err(e) => {
125
+ println!("{}", e);
126
+ println!("{}", flagset);
127
+ process::exit(1);
128
+ }
129
+ Ok(()) => {}
130
+ }
131
+ let coord = point_flag.borrow().get_value::<Point>().ok().unwrap();
132
+ println!("co-ordinates: {:?}", coord);
133
+ }
134
+ ```
0 commit comments