为什么空结构不使用内存?为什么空结构体作为具有其他字段的结构体的字段时会使用内存?

问题描述 投票:0回答:1

我有两个问题让我很困惑。

  1. 为什么空结构不使用内存?如果
    a := struct{}{}
    ,变量
    a
    如何存储在堆栈中。
  2. 当空结构体作为结构体的字段时,会占用内存吗?

游乐场


type EmptyStruct struct {
}

type st1 struct {
    a int64
}

type st2 struct {
    a int64
    b struct{}
}

type st3 struct {
    b struct{}
    a int64
}

func main() {
    const format string = "%-3s: size: %-2d, val: %v\n"

    es := EmptyStruct{}
    s1 := st1{}
    s2 := st2{}
    s3 := st3{}

    fmt.Printf(format, "es", unsafe.Sizeof(es), es)
    fmt.Printf(format, "s1", unsafe.Sizeof(s1), s1)

    fmt.Printf(format, "s2", unsafe.Sizeof(s2), s2)
    fmt.Printf("\t"+format, "s2.a", unsafe.Sizeof(s2.a), s2.a)
    fmt.Printf("\t"+format, "s2.b", unsafe.Sizeof(s2.b), s2.b)

    fmt.Printf(format, "s3", unsafe.Sizeof(s3), s3)
    fmt.Printf("\t"+format, "s3.a", unsafe.Sizeof(s3.a), s3.a)
    fmt.Printf("\t"+format, "s3.b", unsafe.Sizeof(s3.b), s3.b)
}
es : size: 0 , val: {}
s1 : size: 8 , val: {0}
s2 : size: 16, val: {0 {}}
        s2.a: size: 8 , val: 0
        s2.b: size: 0 , val: {}
s3 : size: 8 , val: {{} 0}
        s3.a: size: 8 , val: 0
        s3.b: size: 0 , val: {}

s2
中,空结构体是第二个字段,所有字段都使用8+0 Byte,但是s2使用16 Byte。

s3
中,空struct是第一个字段,所有字段使用8+0 Byte,s3使用8 Byte。

我猜原因是内存对齐,但我不知道如何证明。

go memory memory-management
1个回答
0
投票

检查我的代码版本:

with open('file.txt', 'r') as file_name:
    lines = file_name.readlines()

total = 0
count = 0

for x in lines:
    total += int(x.strip())
    count += 1 

for line in lines:
    print(line.strip())
print('Total', total)
print('Number of random numbers read from the file: ', count)
© www.soinside.com 2019 - 2024. All rights reserved.