Go语言中的判断与分支

主要讲解Go语言中 if、switch 定义和使用

主要知识点:

  • if 关键字普通用法
  • if 表达式中 定义变量,定义的变量只能在 if 作用域中使用
  • swith两种写法示例
  • swith中的 case 自带 break,如果需要继续往下判断执行则需要使用关键字 fallthrough

以下为代码示例:

package main

import (
	"io/ioutil"
	"fmt"
)

// if 普通用法,读取文件示例
func readFile1(){
	const fileName = "abc.txt"
	//在Go中 一个方法可以返回两个值
	contents,err := ioutil.ReadFile(fileName)
	if err !=nil {
		fmt.Println(err) //open abc.txt: The system cannot find the file specified.
	}else{
		fmt.Printf("%s",contents); // xxx 文件内容
	}
}

// if 进阶用法 ,读取文件示例
// 此种写法,在 if 中定义的变量 只能在 if 作用域中使用
func readFile2(){
	const fileName = "abc.txt"
	if contents,err := ioutil.ReadFile(fileName);err !=nil{
		fmt.Println(err) //open abc.txt: The system cannot find the file specified.
	}else{
		fmt.Printf("%s",contents) // xxx 文件内容
		fmt.Println()
	}
}


//Switch 用法1 :switch 后跟变量名
// 此方法模拟四则运算,返回多个值,第二个返回错误信息
func eval(a,b int ,op string) (int,error) {
	switch op{
	case "+":
		return a+b,nil
	case "-":
		return a-b,nil
	case "*":
		return a*b,nil
	case "/":
		return a/b,nil
	default:
		return 0,fmt.Errorf("unsupported operator:"+op)
	}
}
//Switch 用法2
//Switch 后不加表达式的 情况,在case中进行表达式判断,每个case 自带 break,不用自己手动添加 break,
// 如果需要继续往下  判断,需要手工添加 关键字  fallthrough
// 此方法 用于判断 分数所在的 等级
func grade(score int) string{
	g :=""
	switch{
	case score <0 || score >100 :
		//使用 panic 关键字 排除错误后,会中断程序执行
		panic(fmt.Sprintf("Wrong stroe :%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 main() {
	readFile1()
	readFile2()
	fmt.Println(eval(3,4,"+")); //7 <nil>
	fmt.Println(eval(3,4,"*")); //12 <nil>
	fmt.Println(
		grade(0), //F
		grade(59),//F
		grade(79),//C
		grade(89),//B
		grade(99),//A
		grade(100),//A
		//grade(190), //报错,程序中断执行
	)
}

猜你喜欢

转载自my.oschina.net/ruoli/blog/1815455