go基础语法-条件语句

1.if else 语句

if语句后面的条件不需要括号

if n > 0 {
return 1
}else {
return -1
}

'if'之后,条件判断之前,可以初始化变量(作用域为整个if语句),用';'分隔,类似其它语言的for语句

if m := 1 ; n > 0{
return
}else {
fmt.Println(m)
}

2.switch语句

golang中的switch,case语句无需写'break'

switch operator {
case "+":
return a + b
case "-":
return a - b
case "*":
return a * b
case "/":
return a / b
default:
return a*a + b*b

'switch'后可以没有表达式,在case里面写条件

var grade string
switch {
case score < 0 || score > 100:
grade = fmt.Sprintf("Wrong score : %d", score)
case score < 60:
grade = "E"
case score < 70:
grade = "D"
case score < 80:
grade = "C"
case score < 90:
grade = "B"
case score <= 100:
grade = "A"
}
return grade

测试代码

package main
import (
"fmt"
"io/ioutil"
)
/*
if else 测试
*/
func readFile() {
const fileName = "a.txt"
//go语言方法可以有多个返回值
readBytes, err := ioutil.ReadFile(fileName)
//普通写法
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", readBytes)
}
//类似for语句的写法
if readBytes, err := ioutil.ReadFile(fileName); err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", readBytes)
}
}
/*
switch后有表达式
*/
func eval(a, b int, operator string) int {
switch operator {
case "+":
return a + b
case "-":
return a - b
case "*":
return a * b
case "/":
return a / b
default:
panic("unsupported operator : " + operator) //panic中断程序运行并报错
}
}
/*
switch后无表达式和default
*/
func grade(score int) string {
var grade string
switch {
case score < 0 || score > 100:
panic(fmt.Sprintf("Wrong score : %d", score))
//grade = fmt.Sprintf("Wrong score : %d", score)
case score < 60:
grade = "E"
case score < 70:
grade = "D"
case score < 80:
grade = "C"
case score < 90:
grade = "B"
case score <= 100:
grade = "A"
}
return grade
}
func main() {
readFile()
fmt.Println(eval(1, 4, "+"))
fmt.Println(grade(101))
}
上一篇:java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.yunweather.app.db.YunWeatherDB.loadProvinces()' on a null object reference


下一篇:CREATE TABLE 表名 AS SELECT 语句