0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

個人的備忘録:Goの勉強会で学んだ「switch文」の使い方について体系的にまとめてみた

Posted at

はじめに

Go言語のswitch文は、条件に応じた処理の分岐を簡潔に記述できる構文です。

個人の備忘録程度の走り書きとなっておりますが、温かい目で見守っていただければ幸いです。

他の言語とは少し異なる特徴があり、使いこなすことでコードの可読性が高まります。

書こうと思ったきっかけ

受講しているITスクールでGoの勉強会が開催されていて、そこで学んだ内容を整理・復習するためにまとめています。

switch文の基本構文

switch  {
case 値1:
    // 処理1
case 値2:
    // 処理2
default:
    // どのcaseにも該当しない場合の処理
}

例:

package main

import "fmt"

func main() {
    day := "Monday"

    switch day {
    case "Monday":
        fmt.Println("週の始まりです")
    case "Friday":
        fmt.Println("もうすぐ週末です")
    default:
        fmt.Println("通常営業日です")
    }
}

特徴とポイント

  • break が不要(caseが実行されると自動的に抜ける)
  • 複数のcaseに同じ処理を書くことができる(カンマ区切り)
  • switch 式がなくても条件分岐できる(if-elseのような使い方)

式なしswitch(if-else代替):

switch {
case age < 13:
    fmt.Println("子供です")
case age < 20:
    fmt.Println("ティーンエイジャーです")
default:
    fmt.Println("大人です")
}

まとめ

Goのswitch文は、冗長なif-elseを避けつつ、複雑な条件分岐を整理するのに適しています。特にbreak不要、式省略可能といったGo独自の仕様を理解しておくことで、よりスッキリとしたコードが書けるようになります!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?