Golang - 未在转换为float64的接口上定义的比较运算符

时间:2014-07-02 16:39:28

标签: go comparison switch-statement type-conversion

如下面的代码所示,我正在对interface{}进行某种类型切换,以便进行正确的类型切换 - 我尝试将interface{}转换为float64或者string==,然后将其与值进行比较,但是,在float64上使用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) 以外的比较运算符时,Go在建造时抱怨它。

Go吐出的错误如下: -

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

...这是我的代码: -

{{1}}

1 个答案:

答案 0 :(得分:2)

您的问题可能是subval.Valueinterface{},因此比较运算符不可用。我认为在与接口进行相等比较时,请按字节顺序比较基础类型,因此==不会出错。