五、go 分支结构
一、IF语句
package main
import (
"fmt"
"io/ioutil"
)
func main() {
const filename = "abc.txt"
contents, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
}
if
语句还可以类似for
的写法
func main() {
const filename = "abc.txt"
if contents, err := ioutil.ReadFile(filename); err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
}
因为contents
,err
是在if
语句中定义的,所以作用范围只在if
语句内,外面无法访问
if
的条件里可以赋值if
的条件里赋值的变量作用域就在这个if
语句里
二、SWITCH语句
switch
会自动break
,除非使用fallthrough
switch
后可以没有表达式
package main
import (
"fmt"
"io/ioutil"
)
func grade(score int) string {
g := ""
switch score {
case 90:
g = "A"
case 80:
g = "B"
case 50, 60, 70:
g = "C"
default:
g = "D"
}
return g
}
func main() {
fmt.Println(
grade(0),
grade(59),
grade(60),
grade(70),
grade(80),
grade(1111),
)
}
switch
后没有表达式
package main
import (
"fmt"
"io/ioutil"
)
func grade(score int) string {
g := ""
switch {
case score < 0 || score > 100:
panic(fmt.Sprintf("Wrong score: %d", score))
case score < 60:
g = "F"
case score < 80:
g = "C"
case score < 90:
g = "B"
case score <= 100:
g = "A"
}
return g
}
func main() {
fmt.Println(
grade(0),
grade(59),
grade(60),
grade(70),
grade(80),
grade(1111),
)
}