doufu9947 2014-07-02 16:39
浏览 216
已采纳

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

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)
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dqx36753 2014-07-02 19:53
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗