猿问

运算符 > 未为 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)

如何将此类数学运算添加到通用类型元素(数字或字符串)?


繁星淼淼
浏览 178回答 1
1回答

守着一只汪

interface不是类型,也不是表示所有类型(如string和)的交集的通用值int。当您询问是否a大于或等于 时b,您还必须指定这两者属于哪个确切类型(隐含地,它们应该具有相同的类型)才能回答该问题。同样,Go 也需要这些信息。这样做interface可能会有点麻烦。但是,有几种方法:Less在两种类型上分别定义函数:func LessString(n1, n2 string) bool {&nbsp; &nbsp; return strings.Compare(n1, n2) == -1}// no need to define a less function, but whateverfunc LessInt(n1, n2 int) bool {&nbsp; &nbsp; return n1 < n2}或者,使用类型别名:type Name stringtype Age intfunc (name Name) Less(compare string) bool {&nbsp; &nbsp; return strings.Compare(string(name), compare) == -1}func (age Age) LessInt(compare int) bool {&nbsp; &nbsp; return int(age) < compare}Less实现功能的第二种方法interface是进行类型断言:// This isn't all that useful, but whatevertype T interface{}func main() {&nbsp; &nbsp; fmt.Println(Less(10, 20))&nbsp; &nbsp; fmt.Println(Less("10", "20"))}func Less(t1, t2 T) bool {&nbsp; &nbsp; switch v1 := t1.(type) {&nbsp; &nbsp; case string:&nbsp; &nbsp; &nbsp; &nbsp; return strings.Compare(v1, t2.(string)) < 0&nbsp; &nbsp;// import "strings"&nbsp; &nbsp; &nbsp; &nbsp; // return v1 < t2.(string)&nbsp; &nbsp; case int:&nbsp; &nbsp; &nbsp; &nbsp; return v1 < t2.(int)&nbsp; &nbsp; }&nbsp; &nbsp; return false}Go 中没有办法在类型上定义运算符。它更喜欢添加功能来实现这一点。许多标准库模块遵循类似的模式。
随时随地看视频慕课网APP

相关分类

Go
我要回答