by dennis-tra · 1y ago · 0 comments
I assume the thinking was that this is pretty easy to optimise if you care, and if it's on by default there'd then have to be some opt-out which there isn't a good mechanism for.
Good is subjective, but the mechanism is something already implemented: https://pkg.go.dev/structs#HostLayout
What I was hoping not to find (and fortunately didn't!) was one of Go's magical syntactic comments.
The spec defines alignment for numeric types, but that's about it. There is nothing in the spec about struct layout. That is implementation dependent. If you are relying on a particular implementation, you are decidedly in unsafe territory.
> so any change to the default would break a lot of code.
The compiler can disable optimization on cgo calls automatically and most other places where it matters are via the standard library, so it might not be as much as you think. And if you still have a case where it matters, that is what this is for: https://pkg.go.dev/structs#HostLayout
De-facto a lot of programs rely on it, so whatever the spec says is irrelevant.
Not just for cgo by the way, but also things like binary.Read()/Write().
That requires a way to opt out tho, because there are situations where you need a specific field ordering, so now the langage needs to provide way to tune struct compilation behaviour.