1

golang bool类型是怎么实现的

 2 years ago
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.
neoserver,ios ssh client

golang bool类型是怎么实现的

2021-01-18 约 481 字 预计阅读 1 分钟

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的值

通过上面的例子可以说明,boolint8 or uint8无疑。0false非零true

文章作者 guonaihong

上次更新 2021-01-18

老瓶装新酒--使用makefile优化你的工作流 Rfc7230 Header


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK