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

huangapple go评论87阅读模式
英文:

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

问题

我正在尝试使用Go的flag包动态生成FlagSets,并将结果收集到一个从flagname -> flag value的映射中。

我的代码如下:

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, "", "") 
}  

这段代码可以编译通过,但是在解析FlagSet fs之后,映射永远不会被更新,所以"flagA"和"flagB"的值都是""。这对我来说是有道理的;毕竟flags的类型是map[string]string,而不是map[string]*string。不幸的是,我似乎无法使用指针来解决这个问题。我尝试了我能想到的所有引用和解引用的组合,但要么出现空指针解引用(运行时错误),要么出现无效的间接引用(编译时错误)。

如何设置映射和FlagSet,以便在解析FlagSet之后填充映射值呢?

英文:

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?

答案1

得分: 4

以下是代码的翻译:

有什么问题

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

这段代码有什么问题?

英文:

What is wrong with

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

?

huangapple
  • 本文由 发表于 2013年8月8日 15:05:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/18119875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定