Skip to content

Commit

Permalink
Merge pull request #152 from alexflint/mappings-with-commas
Browse files Browse the repository at this point in the history
Add an example of mappings with commas
  • Loading branch information
alexflint authored Apr 20, 2021
2 parents 4354574 + 1e81bb6 commit 9d937ba
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 9d937ba

Please sign in to comment.