前面讲解章节如下:
实战有美眉喝酒小应用
抖音里段子:出来喝点啊,不想去啊。有美眉,走!
package main
import "fmt"
func main() {
var isDrink bool //是否去喝酒 1:true 0:false
var hasGirl bool //是否有美眉 1:true 0:false
fmt.Println("出去喝点吗?")
fmt.Scanln(&isDrink)
if isDrink == true {
fmt.Println("去喝酒")
return
}
fmt.Println("有美眉吗?")
fmt.Scanln(&hasGirl)
if hasGirl {
fmt.Println("去喝酒")
return
}
fmt.Println("待在家里")
}
运行代码
go run main.go
控制流的讲解
编写代码,需要控制程序的执行流程。可以使用条件语句来进行控制。条件语句用于根据条件来执行不同的代码块。
1、if 条件语句
if语句用于根据条件来执行不同的代码块
语句的语法如下:
if 条件语句 {
// 代码块
else if 条件语句 {
// 代码块
} else {
// 代码块
}
示例代码:
a := 3
b := 5
c := 9
if a > b {
fmt.Println("a > b")
} else if (a > c) {
fmt.Println("a > b")
} else {
fmt.Println("a is less num")
}
2、switch case 条件语句
switch 语句用于根据不同的条件执行不同的代码块。
switch 语句的语法如下:
switch 表达式 {
case 值:
// 代码块
case 值:
// 代码块
default:
// 代码块
}
示例代码:
a := 2
switch a {
case 1:
fmt.Println("a Equal 1")
case 2:
fmt.Println("a Equal 2")
default:
fmt.Println("can not checked!")
}
switch语句一般作为空接口中变量类型的判断
func check(v interface{}) {
switch v.(type) {
case int:
fmt.Println(v, "is int")
case string:
fmt.Println(v, "is string")
case bool:
fmt.Println(v, "is bool")
}
}
check(2) // 输出:2 is int
check("Hello") // 输出:Hello is string
chheck(true) // 输出:true is bool