From a84487a43a66f9b51259e2a1f39a2a3e6183808e Mon Sep 17 00:00:00 2001 From: Alex Flint Date: Mon, 19 Apr 2021 21:35:09 -0700 Subject: [PATCH 1/2] updated the example for mappings with commas --- example_test.go | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/example_test.go b/example_test.go index 26f24e7..47a9211 100644 --- a/example_test.go +++ b/example_test.go @@ -95,17 +95,30 @@ func Example_mappings() { // output: map[john:123 mary:456] } +type commaSeparated map[string]string + +func (c commaSeparated) UnmarshalText(b []byte) error { + 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[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 --m one=two,three=four") var args struct { - UserIDs map[string]int + M commaSeparated } MustParse(&args) - fmt.Println(args.UserIDs) - // output: map[john:123 mary:456] + fmt.Println(args.M) + // output: map[one:two three:four] } // This eample demonstrates multiple value arguments that can be mixed with From 1e81bb686691f40ddba12357eccc155681f547a4 Mon Sep 17 00:00:00 2001 From: Alex Flint Date: Tue, 20 Apr 2021 12:23:49 -0700 Subject: [PATCH 2/2] fix the mappings-with-commas example --- example_test.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/example_test.go b/example_test.go index 47a9211..2e9b875 100644 --- a/example_test.go +++ b/example_test.go @@ -95,15 +95,18 @@ func Example_mappings() { // output: map[john:123 mary:456] } -type commaSeparated map[string]string +type commaSeparated struct { + M map[string]string +} -func (c commaSeparated) UnmarshalText(b []byte) error { +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[part[:pos]] = part[pos+1:] + c.M[part[:pos]] = part[pos+1:] } return nil } @@ -111,13 +114,13 @@ func (c commaSeparated) UnmarshalText(b []byte) error { // This example demonstrates arguments with keys and values separated by commas func Example_mappingWithCommas() { // The args you would pass in on the command line - os.Args = split("./example --m one=two,three=four") + os.Args = split("./example --values one=two,three=four") var args struct { - M commaSeparated + Values commaSeparated } MustParse(&args) - fmt.Println(args.M) + fmt.Println(args.Values.M) // output: map[one:two three:four] }