3 ms·
I don't get the interface stuff. If you had a method on an interface, you have to add it to all implementors, or clients won't compile. How is that different fr
by Evbn 14y ago
I don't get the interface stuff. If you had a method on an interface, you have to add it to all implementors, or clients won't compile. How is that different from Java? Java just adds the implements declaration, so Eclispse can help you find those implementations, instead of making you pore over compiler error listings.
- isbadawi 14y agoIn Java, you can run into situations where two classes share a method, but because they don't implement a common interface, for instance because they're part of two different libraries, you can't e.g. write a method that accepts instances of either. You can't straightforwardly take advantage of polymorphism. In Go this is never an issue; you can declare an interface that captures the methods you're interested in, and the existing code automatically implements it. It's kind of like duck typing in python (e.g. this function will work on any object that has a method <x>), except it's statically typed.
- pjmlp 14y agoJust because the method complies to the interface does not mean it does what you would expect from it. static fulfilment != semantic fulfilment.
- msbarnett 14y agoYou could equally say that just because a class declares that it "implements" an interface, it doesn't mean it does what you would expect from it. In practice, there is no language that can save you from people with malicious intent to confuse you. In practice, this is rarely an issue.
- pjmlp 14y agoThere is a big difference. When a developer makes a class implement an interface s/he signing a contract thus validating assumptions. When a type in Go matches an interface, it happens by chance.
- msbarnett 14y agoUtter nonsense. Either a function/method is semantically compatible with the expectations of its caller, or it is not. Whether or not the function/method's author typed the words "implements Foo" has absolutely no impact on this.
- jlouis 14y agoSay you have: Reader - an interface for reading stuff Writer - an interface for writing stuff Some things implement Reader and some things implement Writer. Some things implements both. Now you can declare ReadWriter as in http://golang.org/pkg/io/#ReadWriter http://golang.org/pkg/io/#ReadWriter and everything implementing both will automatically be a member of this newly formed interface. You don't have to go back and tag an "implements ReadWriter" on each of the things you want to implement it. The implementation is implicit if you obey both interfaces. The power is that you can change your interface structure later on in another part of the program, and the existing code just picks it up. You may not even have the source code , or the right to change the source code, so you can't easily tag an 'implements ...' on top of it.