笔记 - unsafe
Package unsafe contains operations that step around the type safety of Go programs.
Packages that import unsafe may be non-portable and are not protected by the Go 1 compatibility guidelines.
unsafe 库让 golang 可以像C语言一样操作计算机内存,但这并不是golang推荐使用的,能不用尽量不用,就像它的名字所表达的一样,它绕过了golang的内存安全原则,是不安全的,容易使你的程序出现莫名其妙的问题,不利于程序的扩展与维护。
unsafe.Sizeof
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. The return value of Sizeof is a Go constant.
func Sizeof(x ArbitraryType) uintptr
unsafe.Sizeof接受任意类型的值(表达式),返回其占用的字节数, 这个大小标识类型存储大小,和类型对应的变量存储的内容大小无关,某些数据类型(int,runne等..) 返回的字节数在32位和64位上有不同。
Sizeof函数返回的大小只包括数据结构中固定的部分,例如字符串对应结构体中的指针和字符串长度部分,但是并不包含指针指向的字符串的内容。Go语言中非聚合类型通常有一个固定的大小,尽管在不同工具链下生成的实际大小可能会有所不同。考虑到可移植性,引用类型或包含引用类型的大小在32位平台上是4个字节,在64位平台上是8个字节。
例:对于整型来说,占用的字节数意味着这个类型存储数字范围的大小,比如int8占用一个字节,也就是8bit,所以它可以存储的大小范围是-128~~127,也就是−2^(n-1)到2^(n-1)−1,n表示bit,int8表示8bit,int16表示16bit,其他以此类推。
常用数据类型对应的存储字节大小(Sizeof输出):
代码实测输出: 32位
package main
import (
"fmt"
"unsafe"
)
func main() {
var v_int8 int8
fmt.Println("Size of v_int8", unsafe.Sizeof(v_int8))
var v_int int
fmt.Println("Size of v_int", unsafe.Sizeof(v_int))
str := "hello"
fmt.Println("Size of str", unsafe.Sizeof(str)) //16
str1 := "morehello"
fmt.Println("Size of str1", unsafe.Sizeof(str1)) //16
slice1 := []int{1,2,3}
fmt.Println("Size of slice1", unsafe.Sizeof(slice1)) //12
var v_runne rune
fmt.Println("Size of v_runne", unsafe.Sizeof(v_runne))
s := make([]int32, 1000)
fmt.Println("Size of []int32:", unsafe.Sizeof(s))//12
fmt.Println("Size of [1000]int32:", unsafe.Sizeof([1000]int32{})) //1000*4
fmt.Println("Real size of s:", unsafe.Sizeof(s)+unsafe.Sizeof([1000]int32{})) //12+1000*4
}
输出:
Size of v_int8 1Size of v_int 4
Size of str 8
Size of str1 8
Size of slice1 12
Size of v_runne 4
Size of []int32: 12
Size of [1000]int32: 4000
Real size of s: 4012
有疑问加站长微信联系(非本文作者)