by rakoo · 11y ago · 0 comments
There's a Go idiom for that. If you have
type Doer interface {
Do()
}
and a type thing struct {
}
and you want to make sure that `thing`s implement `Doer`, just add this line: var _ Doer = thing{}
_ is a special value that can be redefined at will, so the pattern can be used as many times as needed. From there, the meaning should be straightforward: _ is a `thing` that implements `Doer`, so the compiler will check it. You get to keep implicit interfaces, that you can make explicit as you need.Apart from that, this post is really great; as someone "used" to Go and not at all to Rust this kind of impressions is always enlightening.
Then make a Draw() method on the single object default to what you expect. The simple inline explanation is:
type SingleObject struct {
Cowboy
Shape
}
Access is as follows to be unambiguous: Woody.Cowboy.Draw()
Woody.Shape.Draw()They all are the same interface and can be passed into each other's methods, leading to a logical error.
Yes, sometimes this isn't an option when you want to satisfy the interface for two different libraries, but I've not seen this occur very often. More likely you're in control of one of the interfaces; so rename your method to be more descriptive.
This is assumed in the description of the problem. Go has no solution for it. (Java doesn't either, but this is one of the things that C# got right over Java; it's unfortunate that Go has the same issue.)
> , but I've not seen this occur very often.
Sure, it's a problem in theory. Whether it's a problem in practice is a different question. I'd be interested to see examples of this problem in the wild.
https://play.golang.org/p/t0gjJHjU7y
Edit: another variation on the same idea: https://play.golang.org/p/FqSFpMKQuv
There is a paragraph in the faq (https://golang.org/doc/faq#guarantee_satisfies_interface) and one in "Effective Go" (https://golang.org/doc/effective_go.html#blank_implements), but I couldn't find much more than that.