1

I'm trying to use Go's flag package to dynamically generate FlagSets and collect the results in a map from flagname -> flag value.

My code looks like this:

import "flag"

fs := flag.NewFlagSet(strings.Join(commands, " "), flag.ExitOnError)
requiredFlags := []string{"flagA", "flagB"}
flags := make(map[string]string)

for _, f := range requiredFlags { 
    flags[f] = *fs.String(f, "", "") 
}  

This code compiles, but the map never gets updated after the FlagSet fs is parsed, so the values of "flagA" and "flagB" are both "". So this makes sense to me; flags is of type map[string]string after all, not map[string]*string. Unfortunately, I can't seem to fix this problem using pointers. I've tried every combination of referencing and dereferencing I can think of and I either end up with a nil pointer dereference (runtime error) or invalid indirect (compile time error).

How can I set up the map and FlagSet such that the map values are populated after the FlagSet is parsed?

Benjamin Malley
  • 233
  • 4
  • 14

1 Answers1

4

What is wrong with

flags := make(map[string]*string)
for _, f := range requiredFlags { 
    flags[f] = fs.String(f, "", "") 
}
...
println(*(flags["flagA"]))

?

Volker
  • 40,468
  • 7
  • 81
  • 87
  • Nothing at all. I had thought I tried that but it turns out I didn't. Thanks! – Benjamin Malley Aug 08 '13 at 07:13
  • 1
    While reading the question title and response, I perceived it differently. In short, we cannot get address to a map value. See [this question.](https://stackoverflow.com/questions/32495402/why-does-go-forbid-taking-the-address-of-map-member-yet-allows-slice-el) – rohitmohta Dec 04 '17 at 20:57