package main
import (
"io/ioutil"
"fmt"
)
func grade(score int) string{
g:=""
switch {//可以省略掉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 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
}
func main() {
const filename = "abc.txt"
//contents,err:= ioutil.ReadFile(filename)
//if err !=nil {
// fmt.Println(err)
//}else {
// fmt.Printf("%s\n",contents)
//}
//简便写法,if的条件里可以赋值,条件里赋值的变量作用域就在这个if语句里
if contents,err:= ioutil.ReadFile(filename);err !=nil{
fmt.Println(err)
}else {
fmt.Printf("%s\n",contents)
}
fmt.Printf("%s\n",grade(99))
fmt.Println(eval(1,2,"*"))
}
以上是条件语句
if条件里可以定义变量
switch不需要break,也可以直接switch多个条件
package main import ( "fmt" "strconv" "os" "bufio" ) func convertToBin(n int) string{ result :="" for ;n > 0 ; n /= 2 { lsb:=n % 2 result = strconv.Itoa(lsb) + result } return result } 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()) } } func main() { fmt.Println( convertToBin(5), convertToBin(128), ) printFile("abc.txt") }
以上是循环语法
for的条件里不需要括号,可以省略初始条件,结束条件,递增表达式(亦可以全部省略,为死循环)
panic()当程序报错时,会停掉程序,打印出错误