// Investigating the size of structs in Go // @author gtowell // Created: Nov 12, 2021 package main import ( "fmt" "unsafe" ) // a basic structure type s1 struct { a1 bool a2 string a3 bool } // struct with same content // NOT structurally equivalent type s2 struct { a1 bool a3 bool a2 string } // struct with embedded struct (no name on the field) type s3 struct { *s3 a1 int16 } // struct with included struct (it it has its own named field) type s4 struct { s2 s2 a1 int16 } func main() { var b = true var s = "01234567890123456789012345678901234567890123456789" fmt.Printf("bool and string: %d %d\n", unsafe.Sizeof(b), unsafe.Sizeof(s)) var as1 = s1{true, "ajkzdhfkusdhfeuridsihfidshfukhdsfkuhsdkufghsdukfhuewru", true} var as2 = s2{true, true, "a"} fmt.Printf("Struct of 2 bool and 1 string%d %d\n", unsafe.Sizeof(as1), unsafe.Sizeof(as2)) var as3 s3 as3.a1 = 30 as3.s2.a1=true // the a1 var defined in s2 is not hidden, just awkward to access as3.a2 = "hello" as3.a3 = true fmt.Printf("Struct of embedded struct and int16 %d %v\n", unsafe.Sizeof(as3), as3) var as4 s4 as4.s2.a2="hello" fmt.Printf("Struct of struct and int16 %d %v\n", unsafe.Sizeof(as4), as4) }