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

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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?