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

x33g5p2x  于2022-02-07 转载在 Go  
字(0.5k)|赞(0)|评价(0)|浏览(272)

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)

相关文章

微信公众号

最新文章

更多