Menu
CoddyTech

switch 不会贯穿执行

Coddy 面向 PHP 开发者的 Go 课程的第 9 课,共 48 课。

PHP 的 switch 可以贯穿后续 case,并按照 PHP 的相等规则进行比较。Go 的 switch 默认不会贯穿后续 case,比较也会经过静态检查。不要在 Go 的整数 switch 中依赖 PHP 对字符串代码的宽松类型转换。

Go 的 switch 在匹配到 case 后会停止,除非明确写出 fallthrough。多个值可以共用一个 case。不带表达式的 switch 会按顺序检查一系列布尔条件。不必在每个 case 后都添加 break。

PHP 示例

<?php

$code=2;switch($code){case 1:echo "one\n";break;case 2:echo "two\n";break;default:echo "other\n";}

源代码输出:

two

Go 示例

package main
import ("fmt")

func main(){switch 3 { case 1, 3: fmt.Println("odd small"); default: fmt.Println("other") }}

Go 输出:

odd small
challenge icon

挑战

简单

将输入值 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)
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 PHP 开发者的 Go中的所有课

自己练习: Go 在线编译器