by kuschku · 11y ago · 0 comments
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)
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.
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?