Merge pull request #152 from alexflint/mappings-with-commas

Add an example of mappings with commas
This commit is contained in:
Alex Flint 2021-04-20 12:26:56 -07:00 committed by GitHub
commit 9d937ba6c9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 21 additions and 5 deletions

View File

@ -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