if-statement - GoLang,如何编写多行if条件语句

标签 if-statement go comparison

我想将下面的 a 值与 bcde, f 一次而不是像这样写多次。

我的值(value)观是:

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}

a 值应该在 if 语句中使用一次。有什么简单的方法吗?

最佳答案

实际上,您可以使用单个 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?

关于if-statement - GoLang,如何编写多行if条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48571091/

相关文章:

arrays - 如何构建 if 语句并与各种值进行比较?

jquery - 检查 url 的一部分

syntax - Go是否接受变量中的空格,就像下划线一样?它有什么作用?

go - 为什么我用 openssl 和 golang 生成的 RSA 签名不同?

sql-server - SQL Server - 比较相同列中数据的 2 个表而不检查是否相等

c - 为什么变量在比较时会变成零?

python - 有什么办法可以减少 if 语句的数量吗?

javascript - 关于计数的 Stop If 和 Else 语句

c++ - 如果用户输入 q 如何退出

json - 无法将 float32 值解码为字符串