
unsafe.Sizeof浅析
package main import "unsafe"
import "fmt" func main() {
slice := []int{1, 2, 3}
fmt.Println(unsafe.Sizeof(slice)) const (
a = "abc"
b = len(a)
c = unsafe.Sizeof(a)
)
println(a, b, c)
}
在32位机上输出结果是:
12
abc 3 8
在64位机器上输出结果是:
24
abc 3 16
官方文档
Sizeof takes an expression x of any type and returns the size in bytes of a hypothetical variable v as if v was declared via var v = x.
The size does not include any memory possibly referenced by x. For instance, if x is a slice, Sizeof returns the size of the slice descriptor,
not the size of the memory referenced by the slice.
换成数组:
package main import "unsafe"
import "fmt" func main() { arr := [...]int{1, 2, 3, 4, 5}
fmt.Println(unsafe.Sizeof(arr)) //
arr2 := [...]int{1, 2, 3, 4, 5, 6}
fmt.Println(unsafe.Sizeof(arr2)) //
}
32位机器上输出结果:
20
24
可以看到sizeof(arr)的值是在随着元素的个数的增加而增加
这是为啥?
sizeof总是在编译期就进行求值,而不是在运行时,这意味着,sizeof的返回值可以赋值给常量
字符串类型在 go 里是个结构, 包含指向底层数组的指针和长度,这两部分每部分都是4/ 8 个字节,所以字符串类型大小为 8/16 个字节(32bit/64bit)。