带逗号vs或的布尔开关

时间:2018-03-04 18:29:41

标签: go switch-statement

我知道在Go中,你可以像这样的case语句切换条件:

func ctypeAlpha(b byte) bool {
    return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')
}

switch {
case ctypeAlpha(mysql[i]):
    ...
case mysql[i] == '"' || mysql[i] == '\'' || mysql[i] == '`':
    ...

但是在学习案例中隐式破解,并且要让多个匹配执行相同的代码,你可以使用这样的逗号

switch {
case ctypeAlpha(mysql[i]):
    ...
case mysql[i] == '"', mysql[i] == '\'', mysql[i] == '`':
    ... 

除个人意见外,哪种表现更受青睐?

1 个答案:

答案 0 :(得分:2)

以上都不是。例如,

package main

import "fmt"

func isAlpha(b byte) bool {
    return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')
}

func isPunct(b byte) bool {
    return b == '"' || b == '\'' || b == '`'
}

func main() {
    i := 1
    mysql := make([]byte, i+1)
    mysql[i] = 'A'

    switch b := mysql[i]; {
    case isAlpha(b):
        fmt.Printf("isAlpha(%c)\n", b)
    case isPunct(b):
        fmt.Printf("isPunct(%c\n", b)
    }
}

游乐场:https://play.golang.org/p/9SVWBExm9Xj

输出:

isAlpha(A)

注意:

-gcflags='-m'

inlining call to isAlpha
inlining call to isPunct