2017年12月17日 星期日

Generic with Go?

Hi, I found I had talk about Go with generic have a problem. And it caused by interface{}
Of course, interface is a powerful tool in Go. We can use it as contract to make sure some references must have some method.
But this concept could have some problem when it work with generic.
Consider this:
func X<T>(obj T) T {
    // impl
}
func X<Writer>(obj Writer) string {
    // impl has a little different with common T
}
It seems normal, we need specialize some generic for special type, right?
But the problem coming, Writer is a interface, so anything have Write(assume) method, will fall into this X, it's very awkward. We could accept we will execute the normal version.
Out of expected might be almost the worst thing in computer programming.

I have to say all trick can solve it is not good.
But if drop interface, it will be panic, and I also didn't think that will be good.
I have some suggests, don't specialize interface type, if you can.
If you use anything implement by generic, testing the use case you have to make sure it work as expected.

So just these, writing Go is a interesting trivial.

沒有留言:

張貼留言