トラック
/
Go
Go
/
シラバス
/
条件分岐(`switch`)
条件

条件分岐(`switch`) の Go

1個の演習

条件分岐(`switch`)について

switch文は式を評価し、その値に一致する最初のcaseを実行します。 長いif ... else ifの連鎖に比べて、しばしばすっきりと書ける代替手段です。

基本的な使い方

operatingSystem := "windows"

switch operatingSystem {
case "windows":
    // do something if the operating system is windows
case "linux":
    // do something if the operating system is linux
case "macos":
    // do something if the operating system is macos
default:
    // do something if the operating system is none of the above
}

複数の値は、カンマで区切って1つのcaseにまとめられます。 式がいずれかの値と等しければ、そのcaseが一致します:

switch operatingSystem {
case "windows", "linux":
    // do something if the operating system is windows or linux
case "macos":
    // do something if the operating system is macos
default:
    // do something if the operating system is none of the above
}

式のないswitch

switchの後ろの式は、まるごと省略することもできます。 その場合、各caseには真偽値の式を書き、最初にtrueと評価されたものが実行されます。

age := 21

switch {
case age > 20 && age < 30:
    // do something if age is between 20 and 30
case age == 10:
    // do something if age is equal to 10
default:
    // do something else for every other case
}

初期化文

ifと同じように、switchも式の前に短い初期化文を書くことができます。 そこで宣言した変数のスコープは、switchブロックの中だけです:

switch v := getValue(); {
case v < 0:
    // do something if v is less than 0
case v == 0:
    // do something if v is 0
default:
    // do something else for every other case
}
// v will not be accessible here

fallthrough

fallthroughは、次のcaseの式が一致するかどうかに関わらず、その本体を実行させます。 これはcaseの本体の最後の文でなければならず、また実行する次のcaseが存在する必要があります。

fallthroughは、隣り合うcase同士を互いに依存させるため、慣用的なGoではあまり使われません。 その結果、各caseを単独で考えるのが難しくなり、switch全体が読みにくくなります。 複数のcaseを同じ動作にしたいときは、カンマでまとめるほうが分かりやすくなります。 それ以外の理由で複数のcaseに共通のロジックがある場合は、その共通部分をヘルパー関数として切り出すことを検討しましょう。

s := "hello"

switch s {
case "hello":
    fmt.Println("hello")
    fallthrough
case "world":
    fmt.Println("world") // also runs, even though s != "world"
}
// Output:
// hello
// world

詳しくは、Go by Example: SwitchやGo言語仕様を参照してください。

GitHubで編集 リンクは新しいウィンドウまたはタブで開きます

条件分岐(`switch`)を学習する