If statement 与和或的条件检查失败
我正在尝试合并一些条件检查If statement 与和或的条件检查失败,if-statement,go,If Statement,Go,我正在尝试合并一些条件检查 package main import ( "fmt" "reflect" ) type ActionType string const ( VNFHealthCheck ActionType = "vnf-health-check" CollectAlaramAddToReport ActionType = "write-initial-report" CollectResourcesAddCounters Act
package main
import (
"fmt"
"reflect"
)
type ActionType string
const (
VNFHealthCheck ActionType = "vnf-health-check"
CollectAlaramAddToReport ActionType = "write-initial-report"
CollectResourcesAddCounters ActionType = "abc"
)
func main() {
var action, operationType interface{}
action = nil
operationType = "vnf-health-check"
if operationType == string(VNFHealthCheck) && action != nil && action.(ActionType) == CollectAlaramAddToReport {
fmt.Println("Type is ", reflect.TypeOf(action))
}
}
上述代码不会将任何内容打印为操作!=无检查失败
但是如果情况变为
if operationType == string(VNFHealthCheck) && action != nil && action.(ActionType) == CollectAlaramAddToReport || action.(ActionType) == CollectResourcesAddCounters {
fmt.Println("Hello, playground", reflect.TypeOf(action))
}
恐慌伴随着信息而来
panic:interface conversion:interface{}为nil,不是main.ActionType
如果在或条件周围添加()后条件检查工作正常
if operationType == string(VNFHealthCheck) && action != nil && (action.(ActionType) == CollectAlaramAddToReport || action.(ActionType) == CollectResourcesAddCounters) {
fmt.Println("Hello, playground", reflect.TypeOf(action))
}
这种行为的原因可能是什么。?我找不到任何解释 请参阅。&&
运算符的优先级高于|
。括号是获得您想要的分组所必需的
将值与接口{}
进行比较时,不需要类型断言。如果action
是指定的值之一,则遵循action!=无
。使用这些观察结果,将代码简化为:
if operationType == string(VNFHealthCheck) && (action == CollectAlaramAddToReport || action == CollectResourcesAddCounters) {
fmt.Printf("Hello, playground %T\n", action)
}
看。&&
运算符的优先级高于|
。括号是获得您想要的分组所必需的
将值与接口{}
进行比较时,不需要类型断言。如果action
是指定的值之一,则遵循action!=无
。使用这些观察结果,将代码简化为:
if operationType == string(VNFHealthCheck) && (action == CollectAlaramAddToReport || action == CollectResourcesAddCounters) {
fmt.Printf("Hello, playground %T\n", action)
}
&&
的优先级高于|
在第一种情况下
operationType==字符串(VNFHealthCheck)&&action!=零和动作。(动作类型)=CollectalArmaddToReport | |动作。(动作类型)==CollectResourcesAdCounters
原因action
为nil
,条件变为false | | action.(ActionType)==CollectResourcesAddCounters
。nil
cast触发恐慌
第二个条件变为
false&(action.(ActionType)==CollectAlaramAddToReport | | | action.(ActionType)==collectResourcesAndCounters)
。导致false
使表达式短路,将不会执行强制转换 &&
的优先级高于|
在第一种情况下
operationType==字符串(VNFHealthCheck)&&action!=零和动作。(动作类型)=CollectalArmaddToReport | |动作。(动作类型)==CollectResourcesAdCounters
原因action
为nil
,条件变为false | | action.(ActionType)==CollectResourcesAddCounters
。nil
cast触发恐慌
第二个条件变为false&(action.(ActionType)==CollectAlaramAddToReport | | | action.(ActionType)==collectResourcesAndCounters)
。导致false
使表达式短路,将不会执行强制转换