1.go语言布尔类型
go语言中的布尔类型有两个常量值:true
和false
,0值默认是false。布尔类型经常用在条件判断
语句,或者循环语句
。也可以在逻辑表达式
中。
1.1布尔类型
go
package main
import "fmt"
func main(){
var b1 bool = true
var b2 bool = false
var b3 = true
var b4 = false
b5 := true
b6 := false
fmt.Printf("b1: %v\n",b1)
fmt.Printf("b2: %v\n",b2)
fmt.Printf("b3: %v\n",b3)
fmt.Printf("b4: %v\n",b4)
fmt.Printf("b5: %v\n",b5)
fmt.Printf("b6: %v\n",b6)
}
package main
import "fmt"
func main(){
var b1 bool = true
var b2 bool = false
var b3 = true
var b4 = false
b5 := true
b6 := false
fmt.Printf("b1: %v\n",b1)
fmt.Printf("b2: %v\n",b2)
fmt.Printf("b3: %v\n",b3)
fmt.Printf("b4: %v\n",b4)
fmt.Printf("b5: %v\n",b5)
fmt.Printf("b6: %v\n",b6)
}
条件判断
go
package main
import "fmt"
func main() {
age := 18
ok := age >= 18
fmt.Printf("ok: %v\n",ok)
if ok {
fmt.Printf("成年")
} else {
fmt.Printf("no成年")
}
}
package main
import "fmt"
func main() {
age := 18
ok := age >= 18
fmt.Printf("ok: %v\n",ok)
if ok {
fmt.Printf("成年")
} else {
fmt.Printf("no成年")
}
}
for循环语句
go
packe main
import "fmt"
func main() {
count := 10
for i := 0; i < count; i++ {
fmt.Printf("i= %v\n",i)
}
}
packe main
import "fmt"
func main() {
count := 10
for i := 0; i < count; i++ {
fmt.Printf("i= %v\n",i)
}
}
逻辑表达式
go
package main
import "fmt"
func main() {
age := 18
gender := "男"
if age >= 18 && gender == "男" {
fmt.Printf("成年")
}
}
package main
import "fmt"
func main() {
age := 18
gender := "男"
if age >= 18 && gender == "男" {
fmt.Printf("成年")
}
}
注意:不能使用0或者非0表示真假
go
package main
func main() {
i := 1
if i {
//编译错误
}
}
package main
func main() {
i := 1
if i {
//编译错误
}
}