4 ms·
When a struct implements an interface one has to keep guessing that it really does so (unlike Java, C++ there is nothing in the syntax of go that would show int
by MichaelMoser123 6y ago
When a struct implements an interface one has to keep guessing that it really does so (unlike Java, C++ there is nothing in the syntax of go that would show interface inheritance as a fact), and that really doesn't help the poor guys who have to read/understand/maintain some code. Why did they do that to a language that is based on interfaces?
- rowanseymour 6y agoI often find it useful that implementing an interface is implicit. For example maybe I'm using a library that provides a struct A. I can make another struct B that mocks that functionality for testing, and then everywhere in my code use an interface C that encapsulates A and B. That wouldn't be possible if A had to explicitly declare that it implements C. If you want to explicitly declare that you implement an interface.. just put it in the comments, or it's common to see a line like this after a struct declaration: var _ C = (*A)(nil); It's a way of asserting that A satisfies C.
- MichaelMoser123 6y ago- that's an optional convention, and it is not always followed - not easy to search for this pattern. You are right that go interfaces give you some flexibility with mocking, but i still think it's a questionable choice.
- rowanseymour 6y agoIf the problem is finding implementations of an interface, that's provided by the standard tooling. If you're using VSCode just right-click on an interface and select Find All Implementations.
- MichaelMoser123 6y agoactually i was not using 'standard tooling'; was using vim with YouCompleteMe plugin for code completion. I couldn't get all the VSCode plugins to work well, somehow.
- _ph_ 6y agoWhile sometimes it would be nice to have a source-code confirmation, that struct Foo implements the interfaces Bar and Baz, there is one huge benefit of not requiring to declare the interfaces a struct implements: a struct can implement an interface the struct creator doesn't know about. So you can design new interfaces, which for example structs from the standard library or any third party library happen to implement. You don't have to change the original libraries for that. This is quite a benefit for modularity.