首页 > 解决方案 > 运算符 > 未为 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)

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

标签: go

解决方案


interface不是类型,也不是表示所有类型(如string和)的交集的通用值int。当您询问是否a大于或等于 时b,您还必须指定这两者属于哪个确切类型(隐含地,它们应该具有相同的类型)才能回答该问题。同样,Go 也需要这些信息。这样做interface可能会有点麻烦。但是,有几种方法:

  1. 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
}
  1. 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 中没有办法在类型上定义运算符。它更喜欢添加功能来实现这一点。许多标准库模块遵循类似的模式。


推荐阅读