Hacker News new | past | comments | ask | show | jobs | submit login

I posted a comment about this to the blog, but I released a tool which will generate type-specific source code from a generic definition. Code is at https://github.com/joeshaw/gengen

The abs example could be reduced to:

    import "github.com/joeshaw/gengen/generic"

    func abs(x generic.T) generic.T {
        if x < 0 {
            return -x
        }
        return x
    }
You could then generate different type-specific versions:

    gengen abs.go int32 | gofmt -r 'abs -> absInt32' > abs_int32.go
    gengen abs.go float64 | gofmt -r 'abs -> absFloat64' > abs_float64.go
    ...
The downside is that the API is annoyingly non-generic (a different abs variant for each type) but at least you didn't have to type it in a bunch of times.

I agree that abs() is kind of a toy example, but this approach has helped me a lot for various slice operations like indexing and deleting.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: