Skip to content

Commit aaf2282

Browse files
committed
docs(readme): add usage section
1 parent 9d04413 commit aaf2282

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

README.md

+33
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,36 @@
22

33
`pflag` is a port of the [spf13](https://github.com/spf13/pflag)'s popular fork of the
44
Go package by the same name.
5+
6+
## Usage
7+
8+
```rust
9+
use pflag::{FlagSet, Slice};
10+
use std::net::{IpAddr, Ipv4Addr};
11+
12+
let mut flags = FlagSet::new("name");
13+
14+
// Use higher level methods over add_flag directly.
15+
flags.int8("num", 0, "a flag for a number");
16+
flags.string_p("str", 's', String::from("default value"), "a flag for a String and has a shorthand");
17+
flags.ip_addr_slice(
18+
"addrs",
19+
Slice::from([IpAddr::V4(Ipv4Addr::new(0,0,0,0)), IpAddr::V4(Ipv4Addr::new(127,0,0,1))]),
20+
"a multi-valued flag",
21+
);
22+
23+
let args = "--num=1 -s world --addrs 192.168.1.1,192.168.0.1 --addrs=127.0.0.1 subcommand";
24+
if let Err(err) = flags.parse(args.split(' ')) {
25+
panic!(err);
26+
}
27+
28+
// Retrieving value is very easy with the value_of method.
29+
assert_eq!(*flags.value_of::<i8>("num").unwrap(), 1);
30+
assert_eq!(*flags.value_of::<String>("str").unwrap(), "world");
31+
assert_eq!(flags.value_of::<Slice<IpAddr>>("addrs").unwrap().len(), 3);
32+
33+
// Any non-flag args i.e. positional args can be retrieved by...
34+
let args = flags.args();
35+
assert_eq!(args.len(), 1);
36+
assert_eq!(args[0], "subcommand");
37+
```

0 commit comments

Comments
 (0)