Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Not a Go developer but i've been playing with Go for a toy project, really just to learn it. I had a tiny play with generics in Go when i needed a "min(int, ...int) int" func

    // --- There's no int min() in stdlib -----------------------------------------

    // Option 1. use math.Min() which is defined for float64, benchmarks comparing this with Option 2 & 3:
    //     BenchmarkMinImplementations/math.Min-8          261596238                4.282 ns/op
    //     BenchmarkMinImplementations/minGeneric-8        588252955                2.037 ns/op
    //     BenchmarkMinImplementations/minVariadic-8       413756245                2.827 ns/op

    // Option 2. Generics in Go 1.18, this is generic over int and float but can't support a variadic "b"
    func minGeneric[T constraints.Ordered](a, b T) T {
        if a < b {
            return a
        }
        return b
    }

    // Option 3. I was aiming for a lisp-style (min 1 2.3 -4) and this is variadic but it can't also be generic in 1.18
    func minIntVariadic(a int, bs ...int) int {
        for _, b := range bs {
            if b < a {
                a = b
            }
        }
        return a
    }
Coming from Java there's less to get your head around, e.g. super vs. extends isn't a thing here but otherwise similar.


You can do variadic args, you just have to explicitly label the type in both arguments for some reason, like you did for the non-generic version: https://go.dev/play/p/L6psz_WdETM

(I'm aware it's not actually using the varargs reasonably, typing code on a phone is a pain)


Ha! This is awesome, thank you




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: