Mathematical operations - the generics way

542 views
Skip to first unread message

Endre Simo

unread,
Mar 18, 2022, 1:45:44 PM3/18/22
to golang-nuts
Now that generics are officially supported, I was checking in the Go source if there are some generic implementation of utility methods like Abs, Min, Max etc, but I couldn't find it other than this proposal https://github.com/golang/go/discussions/48287.

Anyone knows if something related has been adopted and implemented in Go 1.18?

fge...@gmail.com

unread,
Mar 19, 2022, 6:22:39 AM3/19/22
to Endre Simo, golang-nuts
some details: https://github.com/golang/go/issues/48918
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/e930b89a-0ba6-46f5-b3ec-7aeb26d8acf9n%40googlegroups.com.
>

Endre Simo

unread,
Mar 22, 2022, 11:58:40 AM3/22/22
to golang-nuts
I found a working version meantime.

// Max returns the bigger value between two numbers.
func Max[T constraints.Ordered](x, y T) T {
if x > y {
return x
}
return y
}

// Abs returns the absolut value of x.
func Abs[T constraints.Signed | constraints.Float](x T) T {
if x < 0 {
return -x
}
return x
}

Paul Hankin

unread,
Mar 25, 2022, 4:34:16 AM3/25/22
to golang-nuts
I don't know if it's important to you, but your Max[float64] isn't compatible with math.Max in the standard library.
For example, Max[float64](NaN, 1) returns 1 rather than NaN.

Reply all
Reply to author
Forward
0 new messages