Wednesday, October 22, 2025
HomeGolangNon Zero Sized Empty Struct - Getting Assist

Non Zero Sized Empty Struct – Getting Assist


I’m making an attempt to know Golang’s struct reminiscence structure. So far as I do know, Go has some similarity with C in time period of the reminiscence structure, each kind has measurement and alignment and a few padding will likely be added into the struct to verify each discipline positioned within the right alignment. However, I can’t clarify this one case:

// Obtainable at: https://play.golang.com/p/aiwYrIi6DX0
bundle principal

import (
	"fmt"
	"unsafe"
)

kind A struct {
	a int32
	b int32
	c struct{}
}

kind B struct {
	c struct{}
	a int32
	b int32
}

func principal() {
	fmt.Println(unsafe.Sizeof(A{})) // prints 12
	fmt.Println(unsafe.Sizeof(B{})) // prints 8
}

So far as I do know, struct{} has 0 measurement and aligned to 1 byte, however why does struct A’s measurement is 12, whereas struct B is 8? It appears, if a struct is ended with an empty struct, they’ll add some padding in the long run of the struct. However, I’m undecided why does Go do that. Is my speculation true? And if it’s true, what’s the explanation?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments