if
func main() {
const filename = "abc.txt"
if contents, err := ioutil.ReadFile(filename);err != nil {
fmt.Printf("%s\n",contents)
}else {
fmt.Println(err)
}
}
- if条件里可以赋值
- if的条件里赋值的变量作用域仅限于if语句内
switch
func eval(a, b int, op string) int {
var result int
switch op {
case "+":
result = a + b
case "-":
result = a - b
case "*":
result = a * b
case "/":
result = a / b
default:
panic("unsupported operator" + op)
}
return result
}
- switch会自动break,除非使用fallthrough
- switch也可以没有表达式
- panic用于报错,让程序停下来
for
func main() {
printFile("abc.txt")
}
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())
}
}
死循环
for {
fmt.Println("hello")
}
- for的条件里不需要括号
- for的条件里可以省略初始化条件,结束条件,递增表达式
- 没有while
网友评论