go - 反射(reflect) Type.Field() 顺序

标签 go reflection go-reflect

我似乎无法在文档中找到它,是否可以保证字段中的顺序与结构中声明的顺序相匹配?我知道这似乎符合逻辑(由于内存布局),而且它似乎也以这种方式执行,但只是确定一下。如果这不能保证,我不希望代码在以后中断。

例如,如果我有

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/

相关文章:

go - 在 Go 中按名称调用结构及其方法?

go - 如何使用反射从另一个函数创建新函数

amazon-web-services - 无 SDK 的 Amazon Transcribe Streaming API

java - 如何在不覆盖的情况下打印对象字段?

go - Golang Gorilla session 无法在Windows10上保存

c# 最安全的方法检查一个类型是否在其接口(interface)中包含一个类型

c# - System.Refelection.Assembly.CreateInstance 在 .NET 4.0 中损坏

go - 类型转换接口(interface) slice

regex - Regexp.FindAllStringSubmatch()中,第二个参数是做什么的?

xml - 在Go中使用unmarshal无法访问命名空间的XML属性