1 개요[ | ]
- Go switch
- 다른 언어와 달리 break를 사용하지 않는다.
- 해당 case 코드블럭이 끝나면 break되는 것과 같다.
2 값 case[ | ]
Go
Copy
package main
import "fmt"
func main() {
weekday := "Saturday"
switch weekday {
case "Saturday":
fmt.Println("Weekend - Saturday")
case "Sunday":
fmt.Println("Weekend - Sunday")
default:
fmt.Println("Weekday")
}
}
Loading
Go
Copy
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.\n", os)
}
}
Loading
3 여러 값 case[ | ]
Go
Copy
package main
import "fmt"
func main() {
for i := 1; i <= 4; i++ {
printDigitParity(i)
}
}
func printDigitParity(num int) {
switch num {
case 1, 3, 5, 7, 9:
fmt.Println(num, "odd")
case 0, 2, 4, 6, 8:
fmt.Println(num, "even")
}
}
Loading
4 조건 case[ | ]
Go
Copy
package main
import "fmt"
func main() {
score := 90
switch {
case score > 80:
fmt.Println("High Score")
case score < 20:
fmt.Println("Low Score")
default:
fmt.Println("Middle Score")
}
}
Loading
Go
Copy
package main
import "fmt"
func main() {
x := 'A'
switch {
case '0' <= x && x <= '9':
fmt.Println("숫자")
case 'a' <= x && x <= 'z':
fmt.Println("소문자")
case 'A' <= x && x <= 'Z':
fmt.Println("대문자")
default:
fmt.Println("특수문자")
}
}
Loading
5 같이 보기[ | ]
6 참고[ | ]
편집자 Jmnote
로그인하시면 댓글을 쓸 수 있습니다.