Last active
August 29, 2015 14:14
-
-
Save giwa/bdccc961c5df68cbd7e9 to your computer and use it in GitHub Desktop.
Go by Example: Switch ref: http://qiita.com/giwa@github/items/bc908b2d39ed24799d20
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
// カンマで区切られた複数の条件もしようかである。更に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") | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ go run switch.go | |
write 2 as two | |
it's the weekend | |
it's before noon |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment