Middle
What size of memory does an empty structure occupy in Go language?
sobes.tech AI
Answer from AI
An empty struct in Go occupies 0 bytes. This is because it contains no fields and therefore does not require memory allocation for storage. The address of an empty struct exists, but it is the same for all empty structs.
Example:
package main
import (
"fmt"
"unsafe"
)
func main() {
type Empty struct{} // Declare an empty struct
var e Empty
fmt.Printf("Size of empty struct: %d bytes\n", unsafe.Sizeof(e)) // Print size
fmt.Printf("Address of empty struct: %p\n", &e) // Print address
var e2 Empty
fmt.Printf("Address of another empty struct: %p\n", &e2) // Address will be the same
s := make([]Empty, 10) // Slice of empty structs
fmt.Printf("Size of slice of 10 empty structs: %d bytes\n", unsafe.Sizeof(s)) // Size of slice (descriptor)
s2 := make([]Empty, 0, 10) // Slice of 0 empty structs with capacity 10
fmt.Printf("Size of slice of 0 empty structs with capacity 10: %d bytes\n", unsafe.Sizeof(s2)) // Size of slice (descriptor)
}
Program output:
Size of empty struct: 0 bytes
Address of empty struct: 0x10dbf58
Address of another empty struct: 0x10dbf58
Size of slice of 10 empty structs: 24 bytes
Size of slice of 0 empty structs with capacity 10: 24 bytes
Note that the size of the slice does not depend on the number of empty structs inside, as the slice itself is a structure (descriptor) containing a pointer to the underlying array, length, and capacity.