diff options
| author | Alex Flint <[email protected]> | 2021-04-20 12:26:56 -0700 |
|---|---|---|
| committer | GitHub <[email protected]> | 2021-04-20 12:26:56 -0700 |
| commit | 9d937ba6c92804fb0880d4f7ce1fd0cbfd239afe (patch) | |
| tree | 62e83959ef02059ea1b75d631cf63a41e1876abf | |
| parent | 43545746150d01bef70ac9b203646a605ea0d40a (diff) | |
| parent | 1e81bb686691f40ddba12357eccc155681f547a4 (diff) | |
Merge pull request #152 from alexflint/mappings-with-commasv1.4.0
Add an example of mappings with commas
| -rw-r--r-- | example_test.go | 26 |
1 files changed, 21 insertions, 5 deletions
diff --git a/example_test.go b/example_test.go index 26f24e7..2e9b875 100644 --- a/example_test.go +++ b/example_test.go @@ -95,17 +95,33 @@ func Example_mappings() { // output: map[john:123 mary:456] } +type commaSeparated struct { + M map[string]string +} + +func (c *commaSeparated) UnmarshalText(b []byte) error { + c.M = make(map[string]string) + for _, part := range strings.Split(string(b), ",") { + pos := strings.Index(part, "=") + if pos == -1 { + return fmt.Errorf("error parsing %q, expected format key=value", part) + } + c.M[part[:pos]] = part[pos+1:] + } + return nil +} + // This example demonstrates arguments with keys and values separated by commas -func Example_mappingsWithCommas() { +func Example_mappingWithCommas() { // The args you would pass in on the command line - os.Args = split("./example --userids john=123 mary=456") + os.Args = split("./example --values one=two,three=four") var args struct { - UserIDs map[string]int + Values commaSeparated } MustParse(&args) - fmt.Println(args.UserIDs) - // output: map[john:123 mary:456] + fmt.Println(args.Values.M) + // output: map[one:two three:four] } // This eample demonstrates multiple value arguments that can be mixed with |
