Go学习:条件语句

编程入门 行业动态 更新时间:2024-10-10 07:25:38

Go学习:条件<a href=https://www.elefans.com/category/jswz/34/1770772.html style=语句"/>

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

总结

  1. go语言的函数是可以返回两个值的,func ReadFile(filename string) ([]byte, error) { return os.ReadFile(filename) },ReadFile这个函数返回一个[]byte, error,byte[]就是文件的内容,error就是读取文件时报的错
  2. if的条件里可以赋值
  3. 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
}

正常执行

错误执行

总结

  1. switch语句后面可以没有表达式,再case里面加入条件就好了
  2. go语言的switch语句是不用自己加break的,自己默认加break,不像java代码那么繁琐,需要自己手动加break,如果没加还会出现穿透
  3. panic中断我们程序的运行来报个错

更多推荐

Go学习:条件语句

本文发布于:2023-07-28 19:27:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1287108.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!