switch 不会贯穿执行
Coddy 面向 C# 开发者的 Go 课程的第 9 课,共 48 课。
C# 要求控制流离开非空的 switch 分支,并且支持 switch 表达式。Go 的普通 case 会自动结束,不需要显式写 break,而且可以包含以逗号分隔的多个选项。Go 的 fallthrough 是一种显式的特殊操作,不等同于 C# 的 goto case。
Go 的 switch 在匹配到 case 后会停止,除非显式写出 fallthrough。多个值可以共用一个 case。不带表达式的 switch 相当于一系列按顺序检查的布尔条件。你不需要在每个 case 后都添加 break。
C# 示例
using System;
using System.Collections.Generic;
using System.Linq;
class Program { static void Main() {
int n=3; switch(n){case 1:case 3:Console.WriteLine("odd small");break;default:Console.WriteLine("other");break;}
} }源代码输出:
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,并保留调用方的输入。集合的标准输出使用 Go 的方括号格式,而不是 JSON。
你的代码写在 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)
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Go中的所有课
自己练习: Go 在线编译器