by dons · 13y ago · 0 comments
An aside, it is not "duck typing" if it involves a static type system.
anyway, you're right, it's not duck typing. Duck typing happens at runtime. With Go, every variable has exactly one type at compile time. Sometimes that type is an interface type. With duck typing, the checking happens at runtime. There's no runtime type checking with Go's interface system.
The only requirement to duck typing is "an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface".
This is exactly how Go's interfaces work. You define the methods you require an argument to have, and then anything that has those methods can be used as that argument, without the original type having any knowledge of the interface that was designed. The only difference between Go and Python in this regard is that Python doesn't actually define what a duck is for a specific method, it is implicitly defined by the methods that are called on it. Go explicitly defines what a duck is, which makes it a hell of a lot easier to know if the object you're passing in qualifies as a duck without reading every line in the damn function.
Yes, go checks that an object is a duck at compile time, that doesn't have anything to do with duck typing.
Structural typing looks for structural isomorphsims - it is total. Duck typing looks at run time compatibility, so long as the runtime accessed portion is the correct signature it passes.
So structural typing is about isomorphisms and duck typing is about checking the correct boxes before entry. Both have the attribute of looking at structure but you cannot expect them to cluster types in the same manner.
In ML* terms I like to think of structural typing making hard clusters and Duck typing allowing for soft clusters.
* No, not that ML.
Except when there is: http://golang.org/ref/spec#Type_assertions
Translated to Go: "When I see a type with methods that satisfy this interface, then it implements this interface."
In either case, type errors are detected at compile time. Some people prefer to use "structural typing" for both (maybe using "implicit structural typing" to describe what can be done in F#), and to use "duck typing" to describe languages without type-checking, where type errors only happen at run time.
But it's all just terminology.