反射类型的Field()顺序

huangapple go评论79阅读模式
英文:

Reflect Type.Field() order

问题

我无法在文档中找到相关信息,是否有保证字段的顺序与结构中声明的顺序相匹配?从逻辑上看,它似乎是符合的(由于内存布局),并且似乎也是按照这种方式执行的,但我只是想确认一下。如果这不是一个保证,我不希望代码以后出现问题。

例如,如果我有以下代码:

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")
}

tags 是否保证为 ["bar", "baz", "barbaz"]

英文:

I can't seem to find it in documentation, is there any guarantee that the order from the fields will match the order declared in the struct? I know it seems like it would logically (due to memory layout),and it seems to perform this way too, but just making sure. I don't want code to break later on if this isn't a guarantee.

For example, if I had

type Foo struct {
	bar    string `tag:&quot;bar&quot;`
	baz    string `tag:&quot;baz&quot;`
	barbaz string `tag:&quot;barbaz&quot;`
}

and I ran this code:

var c Foo
t := reflect.TypeOf(c)
nf := t.NumField()

tags := make([]string, nf)

for f := 0; f &lt; nf; f++ {
	tags[f] = t.Field(f).Tag.Get(&quot;tag&quot;)
}

Would tags be guaranteed to be [&quot;bar&quot;, &quot;baz&quot;, &quot;barbaz&quot;]?

答案1

得分: 10

我在golang-nuts上询问了这个问题,并从Ian Lance Taylor那里得到了一个回答,确认它是按照声明顺序进行的,并且不会改变。

它是按照结构体声明中字段出现的顺序进行的。
它不会改变。如果你发现有一个情况不是按照声明顺序的,请提交一个bug报告。谢谢。

英文:

I asked on golang-nuts about this, and got an answer from Ian Lance Taylor confirming it's declaration order, and will not change.

> 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.

答案2

得分: 7

尽管标准的Go编译器(GC)和GCCGO目前不会重新排序结构体字段,但我不会依赖于任何排序。文档中没有明确的保证。这可能会在将来的版本中完成。

字段重新排序是一种在结构体内部对字段进行内存对齐的技术,而不需要使用填充(不必要地增加结构体的内存表示)。你可以在以下问题中阅读相关内容:

https://stackoverflow.com/questions/9486364/why-cant-c-compilers-rearrange-struct-members-to-eliminate-alignment-padding

英文:

Even though GC (the standard Go compiler) and GCCGO don't reoder struct fields today, I wouldn't rely on any ordering. There are no express guarantees in the documentation. This might be done in a future version of either compiler.

Field reordering is a technique used to memory-align fields inside of a struct without resorting to padding (unnecessarily inflating the struct's memory representation). You can read about it in the following question:

https://stackoverflow.com/questions/9486364/why-cant-c-compilers-rearrange-struct-members-to-eliminate-alignment-padding

huangapple
  • 本文由 发表于 2015年9月4日 15:20:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/32392311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定