3 ms·
I'm not a Go programmer, but this seems like implicit interfaces could bite you in the ass pretty easily. For example if I have a Book class that implements a
by garethadams 13y ago
I'm not a Go programmer, but this seems like implicit interfaces could bite you in the ass pretty easily.
For example if I have a Book class that implements a Read method (to mark the book as having been read, for example) then have I just created something which implements io.Reader?
- dsymonds 13y agoOnly if you had a method with that exact signature: taking a []byte argument and returning an int and an error. You'd have to stretch to have that happen by chance.
- garethadams 13y agoOk, I did think that would be part of it but the only reference I could find in the documentation was at http://golang.org/doc/faq#overloading http://golang.org/doc/faq#overloading which suggested that names are the only thing considered. (The other document I looked at before was http://golang.org/doc/effective_go.html http://golang.org/doc/effective_go.html which didn't help) Fair enough, I did say I was only speculating and I've learned something.
- tjgq 13y agoOnly if your Book.Read method has the same signature as Reader.Read (i.e., not just the same name).
- mseepgood 13y agoThe signature must match as well, not only the name. And even if it matched by coincidence, which is rare enough, in order to mix them up, you would have to be a programmer without any clue what he's programming, randomly combining objects and calling methods without knowing what they're supposed to do.
- pjmlp 13y agoYou just described how off-shoring projects work.
- nknighthb 13y agoAside from the accurate response that the signature needs to match, you must understand that Go's type system is deliberately a meld of a very strict type system, and tools that allow you to beat it into a form of duck typing. It's trying to merge the best parts of two very different worlds. A modest loss of safety is therefore tolerated.
- NateDad 13y agoHonestly, it's only a loss of safety if you randomly throw types you don't understand into functions you don't understand. And actually... most of the time this will do exactly what you want it to do, especially if you're talking about io.Writer and io.Reader.