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

It would be really useful if Go allowed you to define methods against types imported from other packages. That way, you could define whichever interface you needed against those types (using only its public API, of course) and then use those interfaces for collections, generic functions, and the like.

The closest I've gotten to that has been to create a single-member wrapper struct. Go provides a little bit of sugar for that, but it results in a decent amount of boilerplate and explicit wrapping/unwrapping.




Simply embedding the type and writing whatever additional methods you need is actually incredibly easy. The boilerplate beyond what is required to actually define the new functions is really tiny

    type Foo struct {
        pkg.Bar
    }

    func UseIt(b pkg.Bar) error {
        return otherFunc(Foo{b})
    }
I think that's actually one of the places Go works really well. It sounds like you want something like C#'s extension methods, which I don't think are a good thing (I used them a bunch in a past job). The problem with them is that it means your code can spontaneously and mysteriously break if you move it somewhere else that isn't including the project that has the extensions. Extensions seemed nice, but they really only made the code a tiny bit cleaner, and the added complexity did not really make up for it, in my opinion.




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

Search: