Golang - Comparison operator not defined on interface converted to float64

13,303

Your problem is probably that subval.Value is an interface{}, so the comparison operator isn't available. I think that when doing an equality comparison with an interface, go compare the underlying types byte-wise, hence the == not giving an error.

Share:
13,303
Ryan
Author by

Ryan

Updated on June 05, 2022

Comments

  • Ryan
    Ryan almost 2 years

    As shown in the code below, I'm doing some type switching on an interface{} in order to do the correct type switching - I'm trying to convert the interface{} to either a float64 or a string and then comparing it to a value, however, when using a comparison operator other than == on the float64's, Go complains about it when building.

    The errors Go spits out are as follows :-

    invalid operation: (interface {})(val.(float64)) > subval.Value (operator > not defined on interface)
    invalid operation: (interface {})(val.(float64)) >= subval.Value (operator >= not defined on interface)
    invalid operation: (interface {})(val.(float64)) < subval.Value (operator < not defined on interface)
    invalid operation: (interface {})(val.(float64)) <= subval.Value (operator <= not defined on interface)
    

    ...and this is my code:-

    val:= s.FieldByName(subval.Metric).Interface()
    switch val(type) {
    case float64, float32, int:
        switch subval.Type {
        case "greater_than":
            if val.(float64) > subval.Value {
                runAction(subval.Action, Config)
            }
        case "greater_than_or_equal_to":
            if val.(float64) >= subval.Value {
                runAction(subval.Action, Config)
            }
        case "equal_to":
            if val.(float64) == subval.Value {
                runAction(subval.Action, Config)
            }
        case "less_than":
            if val.(float64) < subval.Value {
                runAction(subval.Action, Config)
            }
        case "less_than_or_equal_to":
            if val.(float64) <= subval.Value {
                runAction(subval.Action, Config)
            }
        }
    case string:
        if subval.Type == "equal_to" {
            if val.(string) == subval.Value {
                runAction(subval.Action, Config)
            }
        }
    }