if-elseステートメントswitchステートメント

if-elseステートメント

ifは条件付きステートメントです。ifステートメントの構文は

if condition {  
}

もしcondition真、実行{}の間のコード。

C言語など他の言語とは異なり、囲碁言語だ{ }、それはあっても、必要な{ }文の間に一つだけ。

オプションのif文があるelse ifelse部品が。

if condition {  
} else if condition {
} else {
}

if-elseステートメントはいくつでも使用できますelse if条件判定の順序は上から下です。場合ifelse if条件判定結果が真である、対応するコードブロックが実行されます。何の条件が真でない場合は、elseコードブロックが実行されます。

数が奇数か偶数かを検出する簡単なプログラムを書いてみましょう

//if-else
package main

func main() {
	//a:=9
	//1 基本使用
	//if a>10{
	//	fmt.Println("大于10")
	//}else {
	//	fmt.Println("小于等于10")
	//}

	//2 if -else if -else
	//if a>10{
	//	fmt.Println("大于10")
	//}else if a==10 {
	//	fmt.Println("等于10")
	//}else {
	//	fmt.Println("小于10")
	//}

	//3 不能换行(go语言每一行结尾,需要加一个;  ,每当换行,会自动加;)
	//if a>10{
	//	fmt.Println("大于10")
	//}else if a==10 {
	//	fmt.Println("等于10")
	//}else
	//{
	//	fmt.Println("小于10")
	//}

	//4 条件里可以进行初始化操作(有作用域范围的区别)
	//a:=10;
	//if a<10{
	//if a:=10;a<10{
	//	fmt.Println("xxx")
	//}else {
	//	fmt.Println("yyyy")
	//}
	//fmt.Println(a)

	//fmt.Println(a)
}

switchステートメント

switchは、式の値を一致する可能性のあるオプションのリストと比較し、一致に基づいて対応するコードブロックを実行するために使用される条件ステートメントです。またそれは、より考えることができるif else一般的な方法句。

コードを見る方がテキストよりも理解しやすいです。指の番号を入力として受け取り、その指に対応する名前を出力する簡単な例から始めましょう。たとえば、0は親指、1は人差し指などです。

//switch
package main

func main() {
	// 1 switch 基本使用
	//a:=10
	//switch a {
	//case 1:
	//	fmt.Println("1")
	//case 2:
	//	fmt.Println(2)
	//case 9:
	//	fmt.Println(9)
	//case 10:
	//	fmt.Println("10")
	//}

	//2 default
	//a:=15
	//switch a {
	//case 1:
	//	fmt.Println("1")
	//case 2:
	//	fmt.Println(2)
	//case 9:
	//	fmt.Println(9)
	//case 10:
	//	fmt.Println("10")
	//default:
	//	fmt.Println("不知道")
	//}

	//3 多条件
	//a:=3
	//switch a {
	//case 1,2,3:
	//	fmt.Println("1")
	//case 4,5,6:
	//	fmt.Println(2)
	//case 7,9:
	//	fmt.Println(9)
	//case 10,16:
	//	fmt.Println("10")
	//default:
	//	fmt.Println("不知道")
	//}


	//4 无表达式
	//a:=3
	//switch  {
	//case a==1 || a==3:
	//	fmt.Println("1")
	//case a==4||a==5:
	//	fmt.Println(2)
	//default:
	//	fmt.Println("不知道")
	//}

	//5 fallthrough,无条件执行下一个case
	//a:=1
	//switch  {
	//case a==1 || a==3:
	//	fmt.Println("1")
	//	//fallthrough  //fallthrough 会无条件执行下一个case
	//case a==4||a==5:
	//	fmt.Println(2)
	//	fallthrough
	//default:
	//	fmt.Println("不知道")
	//}
}



おすすめ

転載: www.cnblogs.com/kai-/p/12747378.html