在golang中,是否有用于实现“>”(大于)操作的接口/类型?

huangapple go评论68阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年10月5日 13:40:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/73956275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定