首页 > 解决方案 > 一个案件​​可以执行多个案件吗?

问题描述

我想为 case 执行 case'b''c'case 'a'

foo := 'a'
switch foo {
case 'a':
    // execute both case 'b' and case 'c'
case 'b':
    // only execute case 'b'
case 'c':
    // only execute case 'c'
}

我试图将 case'a'转换为 case 'b',然后将 case'b'转换为 case 'c'if foo == 'a',但是不允许有条件的 fallthrough 语句,它们会抛出"fallthrough statement out of place"错误。

这个问题可以通过将代码从 case'b'和 case复制'c'到 case'a'中来解决,也可以通过使用 switch 语句之外的其他条件分支方法来解决,但是我想知道是否有使用 switch 语句而不复制来解决这个问题案例之间的代码以实现类似的结果。

标签: goswitch-statement

解决方案


几个选项:

if foo == 'a' || foo == 'b' {
    // case 'b'
}
if foo == 'a' || foo == 'c' {
    // case 'c'
}
switch foo {
case 'a':
    b()
    c()
case 'b':
    b()
case 'c':
    c()
}

func b() { /* ... */ }
func c() { /* ... */ }

推荐阅读