drgm51600 2018-02-01 20:20
浏览 227

GoLang,如果有条件,如何编写多行语句

I want to match bellow a value with b, c, d, e, f at once instead of writing multiple times like this.

My values are:

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
}

Is actual working code method I have.

But I want to write it like

if a != b or c or d or e or f {print text}

a value should be used once in if statement. Is there is any easy method?

  • 写回答

2条回答 默认 最新

  • duannima8347 2018-02-01 20:30
    关注

    Actually you may implement this with a single switch statement:

    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")
    }
    

    Output of the above (try it on the Go Playground):

    'a' matches none
    

    Using switch is the cleanest and fastest solution.

    Another solution could be to list the values you want a to compare to, and use a for loop to range over them and do the comparison:

    This is how it could look like:

    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")
    }
    

    Output is the same. Try this one on the Go Playground. Although this is more verbose and less efficient, this has the advantage that the values to compare to can be dynamic, e.g. decided at runtime, while the switch solution must be decided at compile time.

    Also check related question: How do I check the equality of three values elegantly?

    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试