golang bool类型是怎么实现的
source link: https://guonaihong.github.io/post/what-type-of-implementation-is-golang-bool/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
golang bool类型是怎么实现的
wc的时候突然蹦出一个想法,golang bool
是什么类型实现的。会和c
一样吗?
既然有疑问,就做个实验看下。
如果bool的值为true,内存里面的值是?
这里可以使用内存强转的思路看下,是驴子是马拉出来溜溜。这里提醒下,使用内存强转一定要内存对齐,bool
占一个字节。
如果不记得可以使用unsafe.Sizeof
看下bool
的内存占用。下面使用uint8
对内存地址强转
// 声明bool变量
b := true
// 验证下bool占的数据宽度,虽然记忆是1,但还是打印确认下
fmt.Printf("%d", unsafe.Sizeof(b))
// 强转内存对齐,看下值
fmt.Printf("bool value = %d\n", *(*uint8)(unsafe.Pointer(&b)))
//输出:1
从输出上看,bool是1 字节int无疑。这里不纠结uint8
还是int8
不涉及运算。这俩只是对那块内存块的解释不同。
如果给bool
赋值为负数
,是true
还是false
b := false
// 看下负数是true or false
*(*int8)(unsafe.Pointer(&b)) = -100
if b {
fmt.Printf("哈哈。。。证明负数转成bool也是true\n")
}
//输出fmt.Printf的值
通过上面的例子可以说明,bool
是int8 or uint8
无疑。0
为false
,非零
为true
文章作者 guonaihong
上次更新 2021-01-18
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK