1.分支结构
//if条件判断
score := 65
if score >= 90{
fmt.Println("A")
}else if score > 75 {
fmt.Println("B")
}else {
fmt.Println("C")
}
//特殊写法
if score := 80;score >= 90{
fmt.Println("A")
}else if score > 75 {
fmt.Println("B")
}else {
fmt.Println("C")
}
score :=55
switch {
case score>=90:
fmt.Println("优秀")
case score>=75:
fmt.Println("良好")
case score>=60:
fmt.Println("合格")
case score<60&&score>=0:
fmt.Println("不合格")
default:
fmt.Println("无效的输入")
}
switch n:=7;n{
case 1,3,5,7,9:
fmt.Println("奇数")
case 2,4,6,8:
fmt.Println("偶数")
default:
fmt.Println(n)
}
fallthrough语法可以执行满足条件的case的下一个case,是为了兼容C语言中的case设计的。
switch n:=7;n{
case 1,3,5,7,9:
fmt.Println("奇数")
fallthrough
case 2,4,6,8:
fmt.Println("偶数")
default:
fmt.Println(n)
}
select 语句类似于 switch 语句,但是select会随机执行一个可运行的case。
如果没有case可运行,它将阻塞,直到有case可运行。
var c1,c2,c3 chan int
var i1,i2 int
select {
case i1 = <- c1:
fmt.Println(i1)
case c2 <- i2:
fmt.Println(i2)
case i3,ok := <-c3:
if ok{
fmt.Println(i3)
}else {
fmt.Println("c3 is close")
}
default:
fmt.Println("no communitcation")
}
//no communitcation
func test(ch chan <- int) {
for i := 0; i < 10; i++ {
ch <- i
}
}
var ch = make(chan int)
//超时处理
func main() {
go test(ch)
for {
select {
case data := <-ch:
fmt.Println(data)
case <-time.After(time.Second):
fmt.Println("request time out")
}
}
}
ch := make(chan int,5)
fmt.Println(len(ch)) //0
fmt.Println(cap(ch)) //5
data := 0
select {
case ch <- data:
fmt.Println(len(ch)) //1
fmt.Println(cap(ch)) //5
default:
fmt.Println("default")
}
2.循环结构
所有循环类型均可以使用for关键字来完成
for i := 0;i < 10;i++{
fmt.Println(i)
}
这种写法类似于其他编程语言中的while
i := 0
for i < 10{
fmt.Println(i)
i++
}
2.1无限循环
for {
fmt.Println("循环")
}
2.2键值循环
Go语言中可以使用for range遍历数组、切片、字符串、map 及通道(channel)。 通过for range遍历的返回值有以下规律:
- 数组、切片、字符串返回索引和值。
- map返回键和值。
- 通道(channel)只返回通道内的值。
2.3跳出循环
for i := 0; i < 10; i++ {
if i==5 {
break
}
fmt.Println(i) // 0 1 2 3 4
}
2.4继续下次循环
for i := 0; i < 10; i++ {
if i==5 {
continue
}
fmt.Println(i) //0 1 2 3 4 6 7 8 9
}