if 语句
实例:
const filename = "abc.txt"
contents, err := ioutil.ReadFile(filename)
if err != nil{
fmt.Println(err)
}else {
fmt.Printf("%s\n", contents)
}
Go语言中if语句的特殊写法:
可以在if语句后面接;
if contents, err := ioutil.ReadFile(filename); err != nil{
fmt.Println(err)
}else {
fmt.Printf("%s\n", contents)
}
switch 语句
Go语言中的switch语句与其他语言不同,默认情况下 case 语句自带 break
语句,匹配成功后就不会执行后面的 case语句,如果需要执行后面的 case语句,可以使用 fallthrough
。
package main
import "fmt"
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"
//default:
// panic(fmt.Sprintf("Wrong score:%d", score))
}
return g
}
func main() {
fmt.Println(grade(70),grade(59),grade(100))
}
switch 语句还可以被用于 type-switch 来判断某个 interface 变量中实际存储的变量类型。
var x interface{}
switch i := x.(type) {
case nil:
fmt.Printf(" x 的类型 :%T",i)
case int:
fmt.Printf("x 是 int 型")
case float64:
fmt.Printf("x 是 float64 型")
case func(int) float64:
fmt.Printf("x 是 func(int) 型")
case bool, string:
fmt.Printf("x 是 bool 或 string 型" )
default:
fmt.Printf("未知型")
}
fallthrough
fallthrough
会强制执行后面的 case 语句,且它不会去判断下一个 case 的表达式是否为 true。换句话说,fallthrough
会无条件的执行它的下一条case语句,不管这条case语句的值是true
还是false
。
实例:
switch {
case false:
fmt.Println("1、case 条件语句为 false")
fallthrough
case true:
fmt.Println("2、case 条件语句为 true")
fallthrough
case false:
fmt.Println("3、case 条件语句为 false")
fallthrough
case true:
fmt.Println("4、case 条件语句为 true")
case false:
fmt.Println("5、case 条件语句为 false")
fallthrough
default:
fmt.Println("6、默认 case")
}
运行结果:
2、case 条件语句为 true
3、case 条件语句为 false
4、case 条件语句为 true
for
- for的条件里不需要括号
- for的条件里可以省略初始条件,结束条件,递增表达式。
省略初始条件:
package main
import (
"fmt"
"strconv"
)
func convertToBin(n int) string{
result := ""
for ; n>0; n /=2{
lsb := n%2
result = strconv.Itoa(lsb) + result
}
return result
}
func main() {
fmt.Println(convertToBin(5))
}
运行结果:
101
for语句也可以省略初始条件、递增条件。
文件读取:
func readFile(filename string) {
file, err := os.Open(filename)
if err != nil{
// panic用于报错
panic(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan(){
fmt.Println(scanner.Text())
}
}
如果省略初始条件、条件表达式、递增条件,就相当于死循环。
for{
// 死循环
fmt.Println("死循环")
}
Go语言中没有while语句