Reflect Type.Field () order

I can not find it in the documentation, is there a guarantee that the order from the fields will correspond to the order declared in the structure? I know that it looks like this is logical (due to the memory layout), and it seems that is also the case, but just make sure. I do not want the code to be interrupted later if this is not a guarantee.

For example, if I had

type Foo struct { bar string `tag:"bar"` baz string `tag:"baz"` barbaz string `tag:"barbaz"` } 

and I ran this code:

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

Will the tags be ["bar", "baz", "barbaz"] ?

+5
source share
2 answers

Despite the fact that GC (the standard Go compiler) and GCCGO today do not change the fields of the reoder structure, I would not rely on any orders. There are no explicit warranties in the documentation. This can be done in a future version of any compiler.

Field reordering is a method used to align memory within a structure without resorting to filling (unnecessarily inflating the representation of the memory structure). You can read about this in the following question:

Why can't C compilers change structural elements to exclude alignment?

+3
source

I asked golang-nuts about this and received a response from Ian Lance Taylor confirming his order of announcement and will not change.

+1
source

All Articles