英文:
Is there an interface/type in golang for implementing > with generics?
问题
我正在尝试找到一个类似的接口,可以在以下代码中使用:
func SliceMax[T comparable](ts []T) (T, error) {
if len(ts) == 0 {
return 0, errors.New("无法从空切片中获取最大值")
}
m := ts[0]
for _, e := range ts {
if e > m {
m = e
}
}
return m, nil
}
但是comparable
并不起作用(在>
符号上失败)。这里是否有内置的接口,还是我需要编写自己的接口?
英文:
I'm trying to find a comparable-like interface that I can use in the following code:
func SliceMax[T comparable](ts []T) (T, error) {
if len(ts) == 0 {
return 0, errors.New("cannot get max from empty slice")
}
m := ts[0]
for _, e := range ts {
if e > m {
m = e
}
}
return m, nil
}
But comparable doesn't work (it fails on the > sign). Is there a built in interface here or do I need to write my own?
答案1
得分: 3
预定义类型comparable
用于可通过==
和!=
进行比较的事物,不包括大于或小于的比较。你可以使用go exp仓库中的constraints.Ordered
,不过你还需要将return 0, ...
更改为类似var zero T; return zero, ...
的形式,因为例如字符串是可比较的,但没有0值。
这与你的问题直接相关,但作为一个小的代码审查评论,类型为[]T
的值是一个切片,而不是数组(数组具有固定的大小),所以我可能会将函数命名为SliceMax
,并且尽量避免在当前命名为typeArray
的参数名称中包含类型(它既不是一个数组,也不是其元素的类型),选择一些通用的名称,比如ts
,尽管我知道这并不适合每个人的口味。
英文:
The predeclared type comparable
is for things that are comparable with ==
and !=
and doesn't include greater than or less than. You can use constraints.Ordered
from the go exp repository, although you'll also have to change return 0, ...
to something like var zero T; return zero, ...
because for example strings are comparable but don't have 0.
It's not directly relevant to your question, but as a small code-review comment, a value of type []T
is a slice, not an array (an array has a fixed size), so I'd probably call the function SliceMax
and I'd try to avoid including the type (ie: slice or array) in the name of the argument that's currently named typeArray
(it's not an array of type -- it's neither an array nor are its elements a type), and pick something generic like ts
although I know that's not to everyone's taste.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论