3 ms·
Imagine I get an object, I don’t know it’s type – I can’t even check if it implements the VectorAddition, Addition, or Appendable trait, I only see it has a .+
by kuschku 12y ago
Imagine I get an object, I don’t know it’s type – I can’t even check if it implements the VectorAddition, Addition, or Appendable trait, I only see it has a .+ method.
How am I supposed to switch between types being able to do either of these, without listing all types that might occur – as this might not be possible
(I’m thinking about Haskell’s type classes as a solution to this, btw)
- vectorjohn 12y agoPlus is a bad example because you can't do that in Go, but I understand the question. Basically, you don't do that in Go. Go has interfaces, but they're implemented implicitly. So rather than "I get an object", you say, "I get an object that implements interface X", and you use whatever methods X has. That just means its up to you to name interfaces in a reasonable way. Which is one down side - if you have an "Add" method, it's back to your question about what it means to add, depending on the implementation. Nothing does this as well as Haskell as far as I can tell.
- fizzbatter 12y agoYea, as mentioned by vectorjohn, you actually just create an interface for whatever you need. So in your example, you might have an Adder interface that simply checks for the Add() method, but if you know you're going to need VectorAddition, Addition, and Appendable, make a new interface that implements all three, then use that. You can do this in one large interface, or 3 small interfaces that you use to compose a 4th, larger interface (usually the preferred way). Example: type Adder interface { Add() } type VectorAdder interface { VectorAdd() } type Appender interface { Append() } type VectAddAppendable interface { Adder VectorAdder Appender } Make sense? Forgive any lapses in syntax, it's been a long day. But i think this is the solution you were referring to correct? By saying that the object coming in must implement the VectAddAppendable interface, you can be positive that it implements the methods you care about. A good example of this is in Golang's stdlib IO package. There's Reader, Writer, and ReadWriter. ReadWriter simply requires both the Reader and Writer interfaces. It's a very common paradigm. Does that solve your issue?