Go和其他语言switch case语法区别
Go的switch case
case匹配执行后,默认跳出判断,不需要 break 关键字。
Go正确写法:
switch e.Name {
        case "a", "b", "c":
            ...
        }// 去除不合规的JSON字符
for i, ch := range prodBytes {
    switch {
    case ch > '~':
        prodBytes[i] = ' '
    case ch == '\r', ch == '\n', ch == '\t', ch < ' ':
        prodBytes[i] = ' '
    }
}Go错误写法:
// 匹配到 case "a" 或 case "b",都会直接跳过。只有 case "c" 下面的逻辑会执行。
switch e.Name {
        case "a":
        case "b":
        case "c":
            ...
        }PHP的switch case
case匹配执行后,继续执行下个case,跳出不再匹配下一个,要使用 break 关键字
switch (e.Name) {
        case "a":
        case "b":
        case "c":
            ...
        break;
}golang 的 switch 遇到匹配的 case 后,执行完 case 内的代码会直接 break 出来,而 php 中需要手动 break,否则会一直往下匹配,直到找到中断位置结束。
Go语言常见switch case用法
1. 基本用法
func main() {
    var a = "hello"
    switch a {
    case "aaa":
        fmt.Println(11)
    case "hello":
        fmt.Println(1)
    case "world":
        fmt.Println(2)
    default:
        fmt.Println(0)
    }
}2. 一分支case多个并列值
package main
 
import (
    "fmt"
)
 
func main() {
    //根据用户输入的月份,打印该月份所属的季节
    var month byte
    fmt.Print("请输入月份:")
    fmt.Scanln(&month)
    switch month {
        case 3, 4, 5:
            fmt.Println("春天")
        case 6, 7, 8:
            fmt.Println("夏天")
        case 9, 10, 11:
            fmt.Println("秋天")
        case 12, 1, 2:
            fmt.Println("冬天")
        default:
            fmt.Println("输入有误...")
    }
}3. interface{}接口的类型判断
switch a := x.(type): 对于 interface{}接口变量,先赋值保存 变量值 备用,再 case 变量类型
package main
 
import (
    "fmt"
)
 
func main() {
    var x interface{}
    var y = 10
    x=y
    switch i := x.(type) {
    case nil:
        fmt.Printf("x的类型是:%T",i)
    case int:
        fmt.Printf("x是 int 类型")
    case float64:
        fmt.Printf("x是 float64 类型")
    case func(int) float64:
        fmt.Printf("x是func(int)类型")
    case bool,string:
        fmt.Printf("x是bool或者string类型")
    default:
        fmt.Printf("未知型")
    }
}4. 跨越 case 的 fallthrough
Go语言中 case 执行后,不会接着执行下一个 case,但为了兼容一些移植代码,加入了 fallthrough 关键字。
加了fallthrough 后,会直接运行紧跟的后一个 case 或 default 语句,
package main
import "fmt"
func main() {
    var s = "hello"
    switch {
    case s == "world":
        fmt.Println("world")
    case s == "hello":
        fmt.Println("hello")
        fallthrough
    case s != "world":
        fmt.Println("world")
        fallthrough
    case s == "world":
        fmt.Println("world")
    }
}
5. 分支表达式
age := 19
switch {
case age < 18:
    fmt.Println("未成年")
case age >= 18:
    fmt.Println("已成年")
}谈谈 PHP switch case 和其他语言的区别: https://xie.infoq.cn/article/d8af45c6a8a125c2615209fe5
golang switch case语句 简介: https://blog.csdn.net/whatday/article/details/113772678
golang:switch case: https://blog.csdn.net/zhizhengguan/article/details/104914687
 沙滩星空的博客
沙滩星空的博客