如何编写一个通用的最大值函数

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

How to write a generic Max function

问题

你好!以下是你要翻译的内容:

如何编写一个通用的max函数,该函数接受两个值,类型可以是字符串、整数或浮点数,并返回最大值。

type comparable interface {
	constraints.Integer | constraints.Float
}

func max[T comparable](x, y T) T {
	return T(math.Max(float64(x), float64(y)))
}

type customComparable interface {
	comparable | ~string
}

func Max[T customComparable](x, y T) T {
	switch v := T.(type) {
	case string:
		if len(x) > len(y) {
			return T(x)
		} else {
			return T(y)
		}
	case constraints.Integer, constraints.Float:
		return T(max(x, y))
	}
}

这就是我想要的通用max函数,但是Go编译器对此不满意,我在T.(type)上遇到了一个错误:

T (type) is not an expression

我清楚地看到,像Max("abc", 1)这样的代码会引起问题,但是如果我知道编写这样的函数的所有后果,并确保正确的xy类型,是否可以像我上面提到的那样做呢?

英文:

How can I write a generic max function that would take 2 values given of type string or Int or float and return a max value.


type comparable interface {
	constraints.Integer | constraints.Float
}

func max[T comparable](x, y T) T {
	return T(math.Max(float64(x), float64(y)))
}

type customComarable interface {
	comparable |  ~string
}

func Max[T customComarable](x, y T) T {
	switch v := T.(type) {
	case string:
		if len(x) > len(y) {
			return T(x)
		} else {
			return T(y)
		}
	case constraints.Integer, constraints.Float:
		return T(max(x, y))
	}
}

This how I want the generic max function but go compiler is not happy with this I'm getting an error on T.(type)

T (type) is not an expression

I clearly see, things like this Max("abc", 1) would cause problem but given that. If I know all of the consequence of writing such function and ensure proper x and y type would it be possible to do something like I mentoined above.

答案1

得分: 1

使用泛型很简单。这是一个更通用的函数,可以接受可变数量的参数。

func Max[T constraints.Ordered](args ...T) T {
	if len(args) == 0 {
		return *new(T) // T 的零值
	}

	if isNan(args[0]) {
		return args[0]
	}

	max := args[0]
	for _, arg := range args[1:] {

		if isNan(arg) {
			return arg
		}

		if arg > max {
			max = arg
		}
	}
	return max
}

func isNan[T constraints.Ordered](arg T) bool {
	return arg != arg
}
英文:

With generics it is pretty simple. Here is a more versatile function, which accepts variable number of arguments

func Max[T constraints.Ordered](args ...T) T {
	if len(args) == 0 {
		return *new(T) // zero value of T
	}

	if isNan(args[0]) {
		return args[0]
	}

	max := args[0]
	for _, arg := range args[1:] {

		if isNan(arg) {
			return arg
		}

		if arg > max {
			max = arg
		}
	}
	return max
}

func isNan[T constraints.Ordered](arg T) bool {
	return arg != arg
}

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

发表评论

匿名网友

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

确定