The documentation at https://pkg.go.dev/unsafe#Sizeof is accurate. Can you suggest some (brief) text that we could add to make it more clear? Thanks. (Note that the current implementations don't use any headers, and that alignment padding only applies to struct types.)
I think a fair amount of developers are probably unaware that alignment could cause unsafe.Sizeof() to return a value that isn't the sum of each field size.
In the past, I believe I've used unsafe.Sizeof() to debug the ordering of fields in my structs to save memory from misalignment (and add new ones at no cost!). It's been long enough that I forgot it had that behavior and rediscovered it again, but in a mailing list entry rather than the function documentation.
I think something as simple as adding this additional sentence would suffice:
Sizeof takes an expression x of any type and returns the size in bytes of a hypothetical variable v as if v was declared via var v = x. The size does not include any memory possibly referenced by x. For instance, if x is a slice, Sizeof returns the size of the slice descriptor, not the size of the memory referenced by the slice. The size also includes any padding introduced by struct alignment. The return value of Sizeof is a Go constant.
I think this is sufficient to highlight this "edge case" and provides enough context that a developer could search for "struct alignment" if they wanted to learn more.
What version of Go are you using (
go version
)?1.x
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?
I read the documentation for unsafe.Sizeof().
What did you expect to see?
The detail that Sizeof() includes overhead such as headers or alignment padding as I discovered from reading https://groups.google.com/g/golang-nuts/c/TFUoKFUi96A/m/qJmq3sdLCwAJ
What did you see instead?
No mention of these lower-level details other than the clarification that Sizeof() does not chase pointers.
The text was updated successfully, but these errors were encountered: