我正在学习围棋,到目前为止我非常喜欢它。来自 JS 背景,我仍在发现某些模式和最佳实践。
在 Go 中使用对象路径为深度嵌套对象获取和分配值的最佳方法是什么?例如,在 JS 中可以这样做...
var children = [{children:[{children:[{a:1}]}]}]
var child = "0.children.0.children.0".split('.').reduce((c, p) => c[p], children)
child.a = 2
console.log(children[0].children[0].children[0].a)
最佳答案
如果你需要一个通用的解决方案,你可以使用包 reflect
来实现, 但最好尽可能避免使用它(例如,如果您在编译时知道类型和“路径”,只需使用字段 selectors 和 index expressions )。
这是一个演示。设置由 string
指定的“深”值的辅助函数元素可能看起来像这样:
func set(d interface{}, value interface{}, path ...string) {
v := reflect.ValueOf(d)
for _, s := range path {
v = index(v, s)
}
v.Set(reflect.ValueOf(value))
}
index()
上面使用的函数可能如下所示:
func index(v reflect.Value, idx string) reflect.Value {
if i, err := strconv.Atoi(idx); err == nil {
return v.Index(i)
}
return v.FieldByName(idx)
}
我们可以这样测试它:
type Foo struct {
Children []Foo
A int
}
func main() {
x := []Foo{
{
Children: []Foo{
{
Children: []Foo{
{
A: 1,
},
},
},
},
},
}
fmt.Printf("%+v\n", x)
path := "0.Children.0.Children.0.A"
set(x, 2, strings.Split(path, ".")...)
fmt.Printf("%+v\n", x)
}
输出(在 Go Playground 上尝试):
[{Children:[{Children:[{Children:[] A:1}] A:0}] A:0}]
[{Children:[{Children:[{Children:[] A:2}] A:0}] A:0}]
从输出中可以看出,“深”字段A
用 string
表示路径 "0.Children.0.Children.0.A"
从最初的 1
改变至 2
.
请注意结构的字段(在本例中为 Foo.A
和 Foo.Children
)必须导出(必须以大写字母开头),否则其他包将无法访问这些字段,并且它们的值无法更改使用包 reflect
.
无需反射,事先知道类型和“路径”,可以这样做(继续前面的示例):
f := &x[0].Children[0].Children[0]
fmt.Printf("%+v\n", f)
f.A = 3
fmt.Printf("%+v\n", f)
输出(在 Go Playground 上尝试):
&{Children:[] A:2}
&{Children:[] A:3}
这个的一般解决方案(不用反射):
func getFoo(x []Foo, path ...string) (f *Foo) {
for _, s := range path {
if i, err := strconv.Atoi(s); err != nil {
panic(err)
} else {
f = &x[i]
x = f.Children
}
}
return
}
使用它(再次,继续前面的例子):
path = "0.0.0"
f2 := getFoo(x, strings.Split(path, ".")...)
fmt.Printf("%+v\n", f2)
f2.A = 4
fmt.Printf("%+v\n", f2)
输出(在 Go Playground 上尝试):
&{Children:[] A:3}
&{Children:[] A:4}
但请注意,如果我们只处理 int
指数,声明 path
不再有意义成为...string
(即 []string
),一个 int
slice 会更有意义。
关于javascript - Golang为深层嵌套结构赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41338339/