Sizeof(struct{}{})) } 运行上面的例子将会输出: $ go run main.go 0 也就是说,空结构体 struct{} 实例不占据任何的内存空间。 2 空结构体的作用 因为空结构体不占据内存空间,因此被广泛作为各种场景下的占位符使用。一是节省资源,二是空结构体本身就具备很强的语义,即这里不需要任何值,仅作为占位符。
1.不占空间内存 在Go 中,可以使用 unsafe.Sizeof 计算出一个数据类型实例需要占用的字节数。 package main import ("fmt""unsafe") func main() { fmt.Println(unsafe.Sizeof(struct{}{})) } 可以看到,Go 中空结构体 struct{} 是不占用内存空间,不像 C/C++ 中空结构体仍占用 1 字节。 2.空结构体的...
int(unsafe.Sizeof(uint32(0))) 2: int(reflect.TypeOf(uint32(0)).Size()) golang中的 union: package main import ("fmt""reflect""unsafe") type Istruct{ a int32 } type Bstruct{ c [34]int16 } func main() { a := I{0x060302} b := (*B)(unsafe.Pointer(&a)) fmt.Printf("...
package main import ( "fmt" "unsafe" ) type struct1 struct { a bool b int64 c bool } type struct2 struct { x bool y bool z int64 } func main() { fmt.Printf("struct1 大小 %d 对齐系数 %d\n", unsafe.Sizeof(struct1{}), unsafe.Alignof(struct1{})) fmt.Printf("struct1.a 大小...
sizeof Sizeof是golang中获取指定类型占用字节的函数。比如slice结构占用的字节数为24(8+8+8),注意这里说的是指定类型,和类型的值没有关系。类型决定了变量的长度和存储格式(以下均为64位cpu及64位操作系统下) /** type SliceHeader struct{ Data uintptr //8 ...
golang-sizeof.tips 这个网站就可以可视化 struct 的内存布局,但是只支持 8 字节对齐,是个缺点。还有一种方法,就是用 golangci-lint 做静态检测,比如在我的一个项目中检测结果是这样的: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 $ golangci-lint run--disable-all-Emaligned ...
var v struct{} fmt.Println(unsafe.Sizeof(v)) // 0 空结构体的作用 因为空结构体不占据内存空间,因此被广泛作为各种场景下的占位符使用。一是节省资源,二是空结构体本身就具备很强的语义,即这里不需要任何值,仅作为占位符。 实现集合(Set) Go 语言标准库没有提供 Set 的实现,通常使用 map 来代替。事...
int64Size := int64(1) arrSize := make([]int, 0) mapSize := make(map[string]string, 0) structSize := &Model{} funcSize := func() {} chanSize := make(chan int, 10) stringSize := "abcdefg" fmt.Println("bool sizeOf:", unsafe.Sizeof(boolSize)) ...
fmt.Println(unsafe.Sizeof(t))//32 } 3.3结构体内存大小(嵌套结构体) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 type Student struct {;-- --; A a int8 b int8 c int8 d int8 } type A struct {;-- --; m int8 } func main() {;-- --; ...
go的对齐系数可以通过unsafe.Alignof获取,占用长度可以用unsafe.Sizeof获取。unsafe.Alignof 官方文档的描述:For a variable x of any type: unsafe.Alignof(x) is at least 1.For a variable x of struct type: unsafe.Alignof(x) is the largest of all the values unsafe.Alignof(x.f) for each field ...