如果你需要一个通用的解决方案,你可以使用包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}]
从输出中可以看出,string 路径"0.Children.0.Children.0.A" 表示的“深”字段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 切片将产生更有意义。