不会贯穿执行的 Switch
Coddy 面向 GDScript 开发者的 Go 课程的第 9 课,共 48 课。
GDScript 的 match 具有模式分支、通配符 _,不会像普通情况那样隐式贯穿执行。Go 的 switch 也会在选中的 case 执行后停止,只有明确要求时才会贯穿执行。Go 可以省略 switch 表达式,改用按顺序排列的布尔条件。这与 GDScript 的解构模式是不同的机制。
Go 的 switch 在匹配的 case 执行后会停止,除非明确写出 fallthrough。多个值可以共用一个 case。不带表达式的 switch 就像一系列按顺序排列的布尔条件。无需在每个 case 后都添加 break。
GDScript 示例
extends Node
func _ready() -> void:
var n: int = 3
match n:
1,3:
print("odd small")
_:
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,并保留调用方输入。集合的标准输出使用 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)
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 GDScript 开发者的 Go中的所有课
自己练习: Go 在线编译器