go - 运算符 > 未为 T 定义
问题描述
试图检查给定的数字是否小于另一个,所以写了以下内容:
package main
import "fmt"
type T interface {}
func Less(i, j T) bool {
return i > j
}
但得到以下错误:
# command-line-arguments
.\hashmap.go:23:11: invalid operation: i > j (operator > not defined on interface)
如何将此类数学运算添加到通用类型元素(数字或字符串)?
解决方案
interface
不是类型,也不是表示所有类型(如string
和)的交集的通用值int
。当您询问是否a
大于或等于 时b
,您还必须指定这两者属于哪个确切类型(隐含地,它们应该具有相同的类型)才能回答该问题。同样,Go 也需要这些信息。这样做interface
可能会有点麻烦。但是,有几种方法:
Less
在两种类型上分别定义函数:
func LessString(n1, n2 string) bool {
return strings.Compare(n1, n2) == -1
}
// no need to define a less function, but whatever
func LessInt(n1, n2 int) bool {
return n1 < n2
}
或者,使用类型别名:
type Name string
type Age int
func (name Name) Less(compare string) bool {
return strings.Compare(string(name), compare) == -1
}
func (age Age) LessInt(compare int) bool {
return int(age) < compare
}
Less
实现功能的第二种方法interface
是进行类型断言:
// This isn't all that useful, but whatever
type T interface{}
func main() {
fmt.Println(Less(10, 20))
fmt.Println(Less("10", "20"))
}
func Less(t1, t2 T) bool {
switch v1 := t1.(type) {
case string:
return strings.Compare(v1, t2.(string)) < 0 // import "strings"
// return v1 < t2.(string)
case int:
return v1 < t2.(int)
}
return false
}
Go 中没有办法在类型上定义运算符。它更喜欢添加功能来实现这一点。许多标准库模块遵循类似的模式。
推荐阅读
- php - 得到 null 作为响应,但数据正在插入数据库
- javascript - 如何在不将页面重新加载到新 url 的情况下完全更改 url?
- csv - 使用 bq 将 CSV 加载到 Bigquery
- revit-api - 从 Revit 中的 BuiltIn Parameter ElementId 获取 BuiltInParameterId
- python - 如何在 Django 中自定义related_name 参数
- hmail-server - 在 hMailServer 上运行诊断时出现 MXRecord 错误
- c# - 使用 CreateSwapChainForComposition 创建交换链时出现异常
- url-rewriting - 如何排除 urlrewriterules.xml 和 domainplittings.xml 被复制到 serverDeploy 任务上的配置目录
- rabbitmq - RabbitMQ - 处理不可靠的服务
- c# - 将正则表达式模式从 php 转换为 C#