4 ms·
I'm not sure if what Go is doing is "Duck Typing", but there's a huge difference from Python. In Go, something implements an Interface by virtue of having the
by robfig 15y ago
I'm not sure if what Go is doing is "Duck Typing", but there's a huge difference from Python.
In Go, something implements an Interface by virtue of having the right method. No "implements" declaration is necessary. This is statically typed and safe at compile time, while Python is not.
Does anyone know what this feature/pattern is called? As far as I know, Go is the first language to have this feature. Seems different from "Duck Typing" to me..
Reference: http://golang.org/doc/go_faq.html#types http://golang.org/doc/go_faq.html#types
Rather than requiring the programmer to declare ahead of time that two types are related, in Go a type automatically satisfies any interface that specifies a subset of its methods. Besides reducing the bookkeeping, this approach has real advantages. Types can satisfy many interfaces at once, without the complexities of traditional multiple inheritance. Interfaces can be very lightweight—having one or even zero methods in an interface can express useful concepts. Interfaces can be added after the fact if a new idea comes along or for testing—without annotating the original types. Because there are no explicit relationships between types and interfaces, there is no type hierarchy to manage or discuss.
- BrandonM 15y agoYou're exactly describing duck typing. Resolving it at compile time in a static, "safe" way is a useful feature to be sure, but that doesn't mean it's not duck typing. Replace "Go" with "Python" in your final paragraph and it's just as true. Implement __setitem__(key, value) and you can use it in a dict-like way such that you can say "foo[bar] = baz" where foo is an object of your defined type. Define __iter__ on your type and you can now say "for x in foo: ..."
- zem 15y agosounds more like ocaml's structural typing than python's duck typing.