Nan*_*aty -1 comparison if-statement go
我想匹配波纹管a与价值b,c,d,e,f的一次,而不是写多次这样.
我的价值观是:
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
}
Run Code Online (Sandbox Code Playgroud)
是我的实际工作代码方法.
但是我想写它
if a != b or c or d or e or f {print text}
Run Code Online (Sandbox Code Playgroud)
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")
}
Run Code Online (Sandbox Code Playgroud)
以上输出(在Go Playground上试试):
'a' matches none
Run Code Online (Sandbox Code Playgroud)
使用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")
}
Run Code Online (Sandbox Code Playgroud)
输出是一样的.在Go Playground尝试这个.虽然这更加冗长且效率更低,但这具有以下优点:要比较的值可以是动态的,例如在运行时决定,而switch解决方案必须在编译时决定.
还要检查相关问题:如何优雅地检查三个值的相等性?
| 归档时间: |
|
| 查看次数: |
1329 次 |
| 最近记录: |