Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Switch文 | 制御構造
Go入門

bookSwitch文

メニューを表示するにはスワイプしてください

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

index.go

copy
12345678910111213141516171819202122232425262728
package 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 コードブロックの波かっこは省略可能。

question mark

Goでswitch文はどのように開始されますか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  5

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  5
some-alt