fallthrough 없는 switch문
Coddy의 Python 개발자를 위한 Go 코스 레슨. 48개 중 9번째.
Python의 멤버십 검사는 여러 대안이 있음을 나타내는 경우가 많습니다. Go의 switch case에는 일치하는 값을 여러 개 나열할 수 있으며 자동으로 종료됩니다. Go의 switch는 Python의 구조적 match가 아니며 임의의 객체를 구조 분해하지 않습니다.
명시적으로 fallthrough를 작성하지 않는 한 Go의 switch는 일치하는 case 이후 종료됩니다. 여러 값이 하나의 case를 공유할 수 있습니다. 표현식이 없는 switch는 순서가 있는 불리언 조건의 연속처럼 작동합니다. 각 case 뒤에 break를 추가할 필요는 없습니다.
Python 예시
n = 3
if n in (1, 3):
print("odd small")
else:
print("other")소스 출력:
odd smallGo 예시
package main
import ("fmt")
func main(){switch 3 { case 1, 3: fmt.Println("odd small"); default: fmt.Println("other") }}
Go 출력:
odd small챌린지
쉬움정확한 입력 N은 north로, S는 south로, 그 외의 모든 문자열은 unknown으로 매핑하세요.
선언된 API를 구현하고, 출력하지 말고 결과를 반환하세요. 드라이버는 필요한 API를 확인하고 호출자의 입력을 보존합니다. 컬렉션의 stdout 출력에는 JSON이 아닌 Go의 대괄호 형식이 사용됩니다.
코드는 exercise.go에 작성하세요. main.go에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 하나의 평면적인 package main을 유지하고, 두 번째 main을 추가하지 마세요.
직접 해보기
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=L(0); before0:=fmt.Sprint(a0)
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Python 개발자를 위한 Go의 모든 레슨
직접 연습해 보세요: 온라인 Go 컴파일러