Golang Syntax _5
19. 스위치
package main import ( "fmt" "time" ) func main() { fmt.Println("When's Saturday?") today := time.Now().Weekday() switch time.Saturday { case today + 0: fmt.Println("Today.") case today + 1: fmt.Println("Tomorrow.") case today + 2: fmt.Println("In two days.") default: fmt.Println("Too far away.") } }
- Go의 Switch는 break문을 통해 빠져나오지 않고 조건이 일치하는 case문을 마치면 switch문을 종료하게된다.
- 위의 코드를 보면 만약
time.Saturday
가today + 0
와 일치하면today + 1
과today + 2
,default
문은 실행하지 않는다. - Go의 switch에선 조건을 생략할 수 있는데 이를 이용해 if-then-else문을 깔끔하게 작성할 수 있다.
switch옆에 조건이 없는 대신 case문에 조건문이 들어가게되며, 제일 위쪽부터 true인 조건의 case문을 실행한다.package main import ( "fmt" "time" ) func main() { t := time.Now() switch { case t.Hour() < 12: fmt.Println("Good morning!") case t.Hour() < 17: fmt.Println("Good afternoon.") default: fmt.Println("Good evening.") } }
20. 연습문제
complex64
타입과complex128
타입을 통해서 Go 언어의 복소수 지원 기능을 알아봅니다.
세제곱근을 얻기 위해서는, 뉴턴의 방법 (Newton’s method)을 적용하여 다음을 반복 수행합니다:
z = z - (z * z * z - x) / (3 * z * z)
package main import "fmt" func Cbrt(x complex128) complex128 { var z complex128 = 1 for a := 1; a < 10; a++ { z = z - (z * z * z - x) / (3 * z * z) } return z } func main() { fmt.Println(Cbrt(3)) // (1.4422495703074083+0i) }