版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chao2016/article/details/81530195
条件、循环要点
- for, if后面的条件没有括号
- if条件里也可以定义变量
- 没有while
- switch不需要break,也可以直接switch多个条件
1. branch.go:
package main
import (
"io/ioutil"
"fmt"
)
// switch会自动break,除非使用fallthrough;可以swich多条件;panic()报错让程序终止
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 readFile(filename string) {
contents, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
// if的条件里可以赋值,其赋值的变量作用域就在if的block中
if contents, err := ioutil.ReadFile(filename); err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
}
func main() {
const filename = "abc.txt"
readFile(filename)
fmt.Println()
fmt.Println(
grade(0),
grade(56),
grade(82),
grade(100),
//grade(101), // 中断报错
)
}
输出:
abcde
12345
hello
world
abcde
12345
hello
world
F F B A
2. loop.go:
package main
import (
"fmt"
"strconv"
"os"
"bufio"
)
// 十进制转二进制,for中省略初始条件
func convertToBin(n int) string {
result := ""
for ; n>0; n /= 2 {
lsb := n % 2
result = strconv.Itoa(lsb) + result
}
return result
}
// 一行行读文件,for中省略初始条件,相当于while
func printFile(filename string) {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
// 死循环,不要while了
func forever() {
for {
fmt.Println("abc")
}
}
func main() {
fmt.Println(
convertToBin(5), // 101
convertToBin(13), // 1101
convertToBin(72387885),
convertToBin(0),
)
printFile("abc.txt")
//forever()
}
输出:
101 1101 100010100001000110100101101
abcde
12345
hello
world
有疑问加站长微信联系(非本文作者)