reflect: document struct field layout in memory #28989
Labels
compiler/runtime
Issues related to the Go compiler and/or runtime.
Documentation
Issues describing a change to documentation.
NeedsInvestigation
Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.
Milestone
What version of Go are you using (
go version
)?1.11
Does this issue reproduce with the latest release?
Yes
What operating system and processor architecture are you using (
go env
)?N/A
What did you do?
Read the docs, specifically as to (1) whether the memory layout of structures has any predictable qualities, (2) whether reflect's Field() (on either reflect.Type or reflect.Value) finds them in a predictable order.
What did you expect to see?
More detailed information.
Empirically, it appears that fields are always reported in source code order, and are always laid out in source code orde. Gven the AST entries representing the declaration of two struct field identifiers for a given struct, the one that came first will have a lower offset, and its field number, as used by Field() or FieldByIndex(), etc., will also be lower.
I don't think this being untrue breaks any compatibility promises, so it may not be true. It's almost never significant. I've seen one case where behavior of code might actually depend significantly on it, in the behavior of a library using reflect to iterate over structs to synthesize a list of command-line flags at runtime.
To be clear, I'm not necessarily asking that the behavior be codified. I'd also be fine with "the ordering is not guaranteed to be consistent", as long as it's safe to assume that, given a value and type that correspond to the same structure type, Field(i) gives corresponding fields in both of them. But right now, even that is not actually specified, although it's hard to imagine any possible way it could be untrue without breaking all sorts of things.
Note overlap with issue #10014 on struct layout/padding. Really, the substantive new part is probably just the observation that nothing is stated about the semantics of Field(), and that if it's not guaranteed to pick one of source order or memory order, or some order anyway, that would be nice to know.
What did you see instead?
Less detailed information.
The text was updated successfully, but these errors were encountered: