1. 程式人生 > >golang 學習筆記 ---Sizeof

golang 學習筆記 ---Sizeof

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)。