package main
import (
"fmt"
"unsafe"
)
func main(){
v3:= struct {
a byte
b []int
c byte
}{}
fmt.Printf("%d",unsafe.Sizeof(v3))
}
更多评论
```go
[]int 大小为 3个uintptr, 64位系统的话是24字节
a byte 大小为1字节
c byte 大小位1字节
一共是 26,但是我觉得是因为你的书写导致内存分配是这样的
| ---a-------补全8字节|
| ---b-------8字节 array------|
| ---b-------8字节 len------|
| ---b-------8字节 cap-----|
| ---c-------补全8字节|
```
#1
```go
package main
import (
"fmt"
"unsafe"
)
func main() {
v3 := struct {
a byte
b []int
c byte
}{}
fmt.Println(unsafe.Sizeof(v3))
fmt.Println(unsafe.Sizeof(v3.a))
fmt.Println(unsafe.Sizeof(v3.b))
fmt.Println(unsafe.Sizeof(v3.c))
fmt.Println("------------------")
v4 := struct {
b []int
a byte
c byte
}{}
fmt.Println(unsafe.Sizeof(v4))
fmt.Println(unsafe.Sizeof(v4.a))
fmt.Println(unsafe.Sizeof(v4.b))
fmt.Println(unsafe.Sizeof(v4.c))
fmt.Println("------------------")
v5 := struct {
a byte
c byte
b []int
}{}
fmt.Println(unsafe.Sizeof(v5))
fmt.Println(unsafe.Sizeof(v4.a))
fmt.Println(unsafe.Sizeof(v4.b))
fmt.Println(unsafe.Sizeof(v4.c))
}
```
输出
```go
40
1
24
1
------------------
32
1
24
1
------------------
32
1
24
1
```
可以看出来结构体中相同类型的字段最好同时连续声明,可能会节省一些内存
#2