Thursday, 8 August 2013

Can I obtain a pointer to a map value in golang?

Can I obtain a pointer to a map value in golang?

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?

No comments:

Post a Comment