语句"/>
Go学习:条件语句
if语句
条件外赋值
package mainimport ("fmt""io/ioutil"
)func main() {readFile("abc.text")
}func readFile(fileName string) {contents, err := ioutil.ReadFile(fileName)if err != nil {fmt.Println(err)}else {fmt.Printf("%s\n",contents)}}
// 报错输出
// open abcd.text: The system cannot find the file specified.
// 正常输出
// abcd
// 1234
// 5678
条件里赋值
package mainimport ("fmt""io/ioutil"
)func main() {readFile("abc.text")
}
func readFile(fileName string) {if contents, err := ioutil.ReadFile(fileName); err != nil {fmt.Print(err)} else {fmt.Printf("%s\n", contents)}
}
// 报错输出
// open abcd.text: The system cannot find the file specified.
// 正常输出
// abcd
// 1234
// 5678
总结
- go语言的函数是可以返回两个值的,
func ReadFile(filename string) ([]byte, error) { return os.ReadFile(filename) }
,ReadFile这个函数返回一个[]byte, error,byte[]就是文件的内容,error就是读取文件时报的错 - if的条件里可以赋值
- if条件里赋值的变量作用域就在这个if语句里面
switch语句
package mainimport ("fmt""io/ioutil"
)func main() {fmt.Println(grade(59),grade(79),grade(99),)
}func grade(score int) string {res := ""switch {case score < 60:res = "不及格"case score < 80:res = "及格"case score <= 100:res = "优秀"default:panic(fmt.Sprintf("Wrong score: %d", score))}return res
}
正常执行
错误执行
总结
- switch语句后面可以没有表达式,再case里面加入条件就好了
- go语言的switch语句是不用自己加break的,自己默认加break,不像java代码那么繁琐,需要自己手动加break,如果没加还会出现穿透
- panic中断我们程序的运行来报个错
更多推荐
Go学习:条件语句
发布评论