mardi 16 avril 2019

Conditional check with AND and OR is failing

I am trying to combine few conditional check

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

The above code does not print anything as action != nil check fails.

But when if condition changes to

if operationType == string(VNFHealthCheck) && action != nil && action.(ActionType) == CollectAlaramAddToReport || action.(ActionType) == CollectResourcesAddCounters {
        fmt.Println("Hello, playground", reflect.TypeOf(action))
    }

Panic is seen with message panic: interface conversion: interface {} is nil, not main.ActionType

If condition check works fine after adding () around OR condition

if operationType == string(VNFHealthCheck) && action != nil && (action.(ActionType) == CollectAlaramAddToReport || action.(ActionType) == CollectResourcesAddCounters) {
        fmt.Println("Hello, playground", reflect.TypeOf(action))
    }

What could be cause of the behavior.? I couldn't find any explanation.

Aucun commentaire:

Enregistrer un commentaire