type Foo struct {
A *string
B *string
C *string
D *string
}
m := map[string]string{"a": "a_value", "b": "b_value", "c": "c_value", "d": "d_value"}
a, b, c, d := m["a"], m["b"], m["c"], m["d"]
foo := Foo{
A: &a,
B: &b,
C: &c,
D: &d,
}
有没有一种方法来映射值直接复制到结构,而不使用中间局部变量a
,b
,c
,d
?
显然我不能只写
foo := Foo{
A: &m["a"],
B: &m["b"],
C: &m["c"],
D: &m["d"],
}
因为这样Go认为我想获取(不可寻址)值仍在地图中的地址。
为了使其简单,紧凑和可重用,请使用辅助函数或闭包:
p := func(key string) *string {
s := m[key]
return &s
}
foo := Foo{
A: p("a"),
B: p("b"),
C: p("c"),
D: p("d"),
}
在Go Playground上尝试一下。
有关背景和更多选项,请参阅相关内容:如何在Go中执行文字* int64?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句