Golang基礎(chǔ)——流程控制語句
@([07] golang)[Go總結(jié)]
[TOC]
for循環(huán)語句
- go只有for關(guān)鍵字,沒有while和do-while
- for后面的條件表達(dá)式不需要用圓括號
()括起來。 - 左花括號與for同行
判斷語句
判斷語句不需要加()
必須加大括號,且左大括號必須與表達(dá)式同行
if語句
語法:
if 布爾表達(dá)式 {
當(dāng)表達(dá)式為true時(shí),執(zhí)行的語句
}
流程圖:
st=>start: Start
e=>end
op=>operation: 條件為真執(zhí)行的操作
cond=>condition: 判斷條件是否為真?
st->cond
cond(yes)->op
cond(no)->e
op->e
代碼實(shí)例
package main
import "fmt"
func main() {
a := 10
if a < 100 {
fmt.Println(a, "小于100")
}
}
輸出:10小于100
if-else語句
語法
if 布爾表達(dá)式{
/* 在布爾表達(dá)式為 true 時(shí)執(zhí)行 */
}
else{
/* 在布爾表達(dá)式為 false 時(shí)執(zhí)行 */
}
流程圖
st=>start: Start
e=>end
op1=>operation: 條件為真執(zhí)行的操作
op2=>operation: 條件為假時(shí)執(zhí)行的操作
cond=>condition: 判斷條件是否為真?
st->cond
cond(yes)->op1
cond(no)->op2
op2->e
op1->e
if-else if-else多重判斷
語法
if 布爾表達(dá)式1{
/* 在布爾表達(dá)式1為 true 時(shí)執(zhí)行 */
}
esle if 布爾表達(dá)式2{
/* 在布爾表達(dá)式2為 true 時(shí)執(zhí)行 */
}
else{
/* 在布爾表達(dá)式為 false 時(shí)執(zhí)行 */
}
流程圖
st=>start: Start
e=>end
op1=>operation: 表達(dá)式1為真時(shí)執(zhí)行的操作
op2=>operation: 表達(dá)式2為真時(shí)執(zhí)行的操作
op3=>operation: 其他情況執(zhí)行的操作
cond1=>condition: 表達(dá)式1是否為真?
cond2=>condition: 表達(dá)式2是否為真?
st->cond1
cond1(yes)->op1
cond1(no)->cond2
cond2(yes)->op2
cond2(no)->op3
op1->e
op2->e
op3->e
在if之后,條件語句之前,可以添加變量初始化語句,使用
;分割。
如果函數(shù)有返回值,最終的return語句不允許包含在if...else...中,會導(dǎo)致編譯錯(cuò)誤。function ends without a return statement
錯(cuò)誤演示:
func example(x int) int {
if x > 0 {
return 5
} else {
return x
}
}
正確做法
func example(x int) int {
if x > 0 {
return 5
} else {
fmt.Printf("%d ", x)
}
return x
}
switch語句
語法
switch var1 {
case val1:
...
case val2:
...
default:
...
}