Memory alignment problem

type W struct {
    b byte
    i int32
    j int64
}

type W2 struct {
    name string
    age  int32
}

var w W
var w2 W2
fmt.Println(unsafe.Sizeof(w), unsafe.Sizeof(w2))

for the w variable, I know the memory footprint should be 16, but why is w2 24? Ask for advice

Jul.14,2021

I read that unsafe.Sizeof (), string is 16 int32 is 4, press 8 alignment, you are 24


import "fmt"
import "unsafe"

func main() {
    var bs []byte
    fmt.Println("[]byte:", unsafe.Sizeof(bs))
    var str string
    fmt.Println("string:", unsafe.Sizeof(str))
    var i64 int64
    fmt.Println("int64:", unsafe.Sizeof(i64))
    var i32 int64
    fmt.Println("int32:", unsafe.Sizeof(i32))
    var stru struct{}
    fmt.Println("struct:", unsafe.Sizeof(stru))       
}   

this is written on the document

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.
Menu