GoLang,如果condtion如何写一个多行语句

时间:2018-02-01 20:20:45

标签: if-statement go comparison

我希望立即将a值与bcdef匹配,而不是写入多个这样的时候。

我的价值观是:

a = 11
b = 22
c = 33
d = 44
e = 55
f = 66

if a != b && a != c && a != d && a != e && a != f{
    // Do something
} else{
    // Do something else
}

是我的实际工作代码方法。

但我想把它写成

if a != b or c or d or e or f {print text}
在if语句中应该使用

a值一次。有没有简单的方法?

2 个答案:

答案 0 :(得分:7)

实际上,您可以使用单个switch语句实现此目的:

a, b, c, d, e, f := 1, 2, 3, 4, 5, 6

switch a {
case b, c, d, e, f:
    fmt.Println("'a' matches another!")
default:
    fmt.Println("'a' matches none")
}

上述输出(在Go Playground上尝试):

'a' matches none

使用switch是最干净,最快速的解决方案。

另一种解决方案可能是列出您想要a进行比较的值,并使用for循环来对它们进行测距并进行比较:

这就是它的样子:

match := false
for _, v := range []int{b, c, d, e, f} {
    if a == v {
        fmt.Println("'a' matches another!")
        match = true
        break
    }
}
if !match {
    fmt.Println("'a' matches none")
}

输出是一样的。在Go Playground上试试这个。虽然这更加冗长且效率较低,但这具有以下优点:要比较的值可以是动态,例如,在运行时决定,而switch解决方案必须在编译时决定。

同时检查相关问题:How do I check the equality of three values elegantly?

答案 1 :(得分:1)

我会使用switch声明

a := 11
b := 22
c := 33
d := 44
e := 55
f := 66
switch a {
case b, c, d, e, f:
default:
    fmt.Println("Hello, playground")
}