我有两个问题让我很困惑。
a := struct{}{}
,变量a
如何存储在堆栈中。
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。
我猜原因是内存对齐,但我不知道如何证明。
检查我的代码版本:
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)