我想将下面的 a
值与 b
、c
、d
、e
, 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/