branch.go 1.3 KB
Newer Older
_Fighter's avatar
add  
_Fighter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
package main

import (
 "fmt"
 "io/ioutil"
)

func ifcondition()  {
 const filename = "test.txt"
 // ReadFile reads the file named by filename and returns the contents.
 // A successful call returns err == nil, not err == EOF. Because ReadFile
 // reads the whole file, it does not treat an EOF from Read as an error
 // to be reported.
 contents ,err := ioutil.ReadFile(filename)
 // if不需要 括号
 if err != nil{
  fmt.Println(err)
 }else{
  fmt.Printf("%s\n" ,contents)
 }

 // 简单写法
 if  content ,err := ioutil.ReadFile(filename); err != nil{
  fmt.Println(err)
 } else{
  fmt.Printf("%s\n" ,content)
 }
 //fmt.Printf("%s\n" ,content)  此处不能再访问 content ,生命周期在if中,外部不能访问
}

func grade(score int ) string  {
  g:= ""
  // switch 后面可以跟 选择参数,也可以不跟参数
  switch  {
      case score < 0 || score >100:
       // panic 报错并中断程序执行,
        panic(fmt.Sprintf( "Wront score: %d",score))
      case score < 60 :
         g = "不及格"
      case score < 80:
         g = "一般"
      case score < 90:
        g = "良好"
      case score <= 100:
        g = "优秀"
  }
 return g
}


func main() {
   ifcondition()
   fmt.Println(
    grade(33),
    grade(67),
    grade(98),
    grade(81),
    grade(100),
    )

}