我似乎无法在文档中找到它,是否可以保证字段中的顺序与结构中声明的顺序相匹配?我知道这似乎符合逻辑(由于内存布局),而且它似乎也以这种方式执行,但只是确定一下。如果这不能保证,我不希望代码在以后中断。
例如,如果我有
type Foo struct {
bar string `tag:"bar"`
baz string `tag:"baz"`
barbaz string `tag:"barbaz"`
}
然后我运行了这段代码:
var c Foo
t := reflect.TypeOf(c)
nf := t.NumField()
tags := make([]string, nf)
for f := 0; f < nf; f++ {
tags[f] = t.Field(f).Tag.Get("tag")
}
标签
是否保证是["bar", "baz", "barbaz"]
?
最佳答案
我在 golang-nuts 上询问了这个问题,得到了 an answer from Ian Lance Taylor确认申报顺序,不会改变。
It's the order in which the fields appear in the struct declaration. It's not going to change. If you find a case where it is not the order in the declaration, please file a bug. Thanks.
关于go - 反射(reflect) Type.Field() 顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32392311/