2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go by Example: Switch

Last updated at Posted at 2015-01-24

(この記事は Go by Example: Switch を翻訳したものです。)

switchは枝がたくさんある条件分岐を表現します。

package main

import "fmt"
import "time"

func main() {
	// 基本的な例
	i := 2
	fmt.Print("write ", i, " as ")
	switch i {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
	case 3:
		fmt.Println("three")
	}

	// 一つのcase文に複数の条件をカンマ区切りで記述できる。更にdefaultも使用可能である。
	switch time.Now().Weekday() {
	case time.Saturday, time.Sunday:
		fmt.Println("it's the weekend")
	default:
		fmt.Println("it's a weekday")
	}

	// switchの最初の式がないのはif/elseのもう一つのやり方である。
	// caseに不等式を書けることもここで紹介しておく。
	t := time.Now()
	switch {
	case t.Hour() < 12:
		fmt.Println("it's before noon")
	default:
		fmt.Println("it's after noon")
	}
}
$ go run switch.go 
write 2 as two
it's the weekend
it's before noon
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?