[英]Golang - Comparison operator not defined on interface converted to 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. 如下代码所示,我正在对
interface{}
进行某种类型转换,以进行正确的类型转换-我试图将interface{}
转换为float64
或string
,然后将其与一个值,但是,在float64
上使用==
以外的比较运算符时,Go在构建时会抱怨它。
The errors Go spits out are as follows :- Go吐出的错误如下:
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)
}
}
}
Your problem is probably that subval.Value
is an interface{}
, so the comparison operator isn't available. 您的问题可能是
subval.Value
是interface{}
,因此比较运算符不可用。 I think that when doing an equality comparison with an interface, go compare the underlying types byte-wise, hence the ==
not giving an error. 我认为与接口进行相等性比较时,请按字节比较基础类型,因此
==
不会给出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.