英文:
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)
这样的代码会引起问题,但是如果我知道编写这样的函数的所有后果,并确保正确的x
和y
类型,是否可以像我上面提到的那样做呢?
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论