-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Closed
Labels
Description
I have a use case where it would be useful to have a field inside of a struct that gets changed in type from something to type struct{} -- and then no longer takes up space (I want to use golang structs like protobuf message definitions).
When I checked my assumption however, I find a surprise: when the struct{} field is alone, it doesn't take up any space, as expected. But when the struct{} field is with another member, then it takes up 8 bytes. Ouch! It seems like an opportunity for optimization has been missed.
package main
// run on : go version go1.7 darwin/amd64 (osx 10.11.6)
import (
"fmt"
"unsafe"
)
// A is size 0
type A struct {
NotAMystery struct{} // takes up 0 bytes, as expected
}
// B is size 8
type B struct {
Hithere int64 // takes up 8 bytes, as expected.
}
// C is size 16
type C struct {
Hithere int64
Mystery struct{} // takes up 8 bytes, HUH??
}
func main() {
var a A
var b B
var c C
fmt.Printf("size of A is '%v'\n", unsafe.Sizeof(a))
fmt.Printf("size of B is '%v'\n", unsafe.Sizeof(b))
fmt.Printf("size of C is '%v'\n", unsafe.Sizeof(c))
}
/*output
$ go run meas.go
size of A is '0'
size of B is '8'
size of C is '16'
*/