天天看点

Golang系列之布尔类型基本介绍

Golang系列之布尔类型基本介绍

1、基本介绍

go语言中的布尔类型,关键字为bool,布尔类型只有true或者false两种类型,占用1个字节,布尔类型适用于逻辑运算,一般在流程控制语句中,比如if条件、for循环等等

var bol bool = true
fmt.Println("bol=" , bol)      

2、布尔类型字节

布尔类型占用内存空间大小是1个字节,可以通过​

​unsafe.Sizeof​

​打印

var bol bool = true
// 打印布尔类型占用字节 
fmt.Println("size of bool=" , unsafe.Sizeof(bol))      

3、不支持类型强转

var b bool 
// 编译会报错,cannot use 1 (type untyped int) as type bool in assignment
b = 1
// 类型强转也会报错,cannot convert 1 (type untyped int) to type bool
b = bool(1)      
var bolv bool
bolv := (1!=2)
fmt.Println("b11=" , bolv)      

继续阅读