2 ms·
I think duck typing is different from structural typing, and go is not duck typed, but structurally typed. I think the difference is that in duck typing, there
by didibus 7y ago
I think duck typing is different from structural typing, and go is not duck typed, but structurally typed.
I think the difference is that in duck typing, there is no real type. A thing is a duck if I can use it as one, and that same thing can be a chair if I can also use it as one.
So on duck typing, we say, does it have the properties I need, if so I can happily use it, don't care what it is. And that can only be done at runtime, since you can't fully predict the runtime properties the thing will have.
In structural typing, we say that the type of a thing is defined by its structure. This thing is a Duck because it is of the expected structure of a duck, which might be to define a quack string -> string method. At this point, you say the thing is a Duck. You can do this at compile time, because you have defined statically a set of named things and their structure, and then you can track the things passed to you and match their structure to the list of structures you have to find the one that fits and consider it of that type.
- samatman 7y agoI agree, and the difference is easy to illustrate. quack() in duck typing, has to have no arguments and return a string (let's say). We can have a NotarizedDuck class where quack(true) instead returns the number of times the NotarizedDuck has quacked, so long as quack() itself returns a string, it will pass the unit test. In structural typing, it's illegal to call that quack, because it's the wrong function signature.