The order of the members in the struct is different, resulting in different memory usage. Are there any principles that follow in the order in which member types are defined?

background: on 64-bit operating system

example: define 2 stuct objects with the same members (in different order) and print

package main

import "unsafe"

type A struct {
    X bool
    Y float64
    Z int16
}

type B struct {
    Y float64
    X bool
    Z int16
}

func main() {
    print("A: ")
    println(unsafe.Sizeof(A{}))
    print("B: ")
    println(unsafe.Sizeof(B{}))
}

output result:

A: 24
B16

conclusion:
so when defining sturct members, random definitions may result in different memory usage. What I want to ask is, is there anything to refer to in the definition?


I wonder if you know the memory alignment in C? It's the same thing here

because of your structure, float64, causes the members of the whole structure to be aligned in 64 bits (that is, 8 bytes)

for A br X Y and Z 8 bytes each, that is 24 bytes

for BMague Y 8 bytes, while X and Z can be put down in an 8 byte space, so they share 8 bytes

the conclusion is obvious

you can use this website to view the internal storage layout of a structure

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b37001-2c061.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b37001-2c061.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?