Switch文
メニューを表示するにはスワイプしてください
switch文は、式を複数の値と比較するための便利な方法。
以下はswitch文の基本構文:
switch (expression) {
case value1: {
// Code to be executed if the expression equals value1
}
case value2: {
// Code to be executed if the expression equals value2
}
case ...
...
default: {
// Code to be executed if the expression doesn't match any of the values
}
}
switch文に関する重要なポイント:
expressionは一度だけ評価され、その値が各caseで指定された値と比較される;- 一致した
caseの下のコードブロックが実行され、残りのcaseは無視される; - どの
caseにも一致しない場合、defaultの下のコードブロックが実行される。defaultは省略可能。
以下は、プログラム内でswitchを使用する例:
index.go
12345678910111213141516171819202122232425262728package main import "fmt" func main() { // Let's create a program that prints a message based on the day of the week. dayOfWeek := 5 // Assuming it's Friday switch dayOfWeek { case 1: fmt.Println("It's Monday! Start the week with enthusiasm.") case 2: fmt.Println("It's Tuesday! Keep pushing forward.") case 3: fmt.Println("It's Wednesday! Halfway through the week.") case 4: fmt.Println("It's Thursday! Almost there, don't give up.") case 5: fmt.Println("It's Friday! Time to celebrate the weekend.") case 6: fmt.Println("It's Saturday! Enjoy your day off.") case 7: fmt.Println("It's Sunday! Relax and recharge for the week ahead.") default: fmt.Println("Invalid day of the week.") } }
注意
caseコードブロックの波かっこは省略可能。
すべて明確でしたか?
フィードバックありがとうございます!
セクション 3. 章 5
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 3. 章 5