4 ms·
Duck typing (horror) in Go
- loosescrews 2y agoSo Go supports both structural and duck typing? Why is that a problem?
- tgv 2y agoIt doesn't support duck typing in the usual sense, but unchecked type casting 'any' to an interface does indeed compile. To any type, as a matter of fact.
- randomdata 2y ago> It doesn't support duck typing in the usual sense The article is about how it does support duck typing in the usual sense. Why do you disagree?
- tgv 2y agoIt doesn't try to call the method. It never gets there. The value/object is never seen as a Duck. It's not using a value as an arbitrary type. It was cast to any (which always succeeds), and then to something with a specific interface. It panics on the type cast. That's in the language spec: if you type-cast without checking the result, you can get a panic. I don;t consider C a duck typing language too, because you can write ((Bird*) ptr)->swim(), but perhaps you do?
- randomdata 2y ago> It doesn't try to call the method. It never gets there. Sure, same as any other language with duck typing. Consider Ruby, which is famous for its duck typing. `variable.not_a_method` raises NoMethodError. How do you think it knows to do that? That's right, it first performs a type check and, since that check fails, it doesn't try to call the method and instead raises the exception. Exactly the same as Go panicking under the same circumstances. > and then to something with a specific interface. That is a type assertion, not a cast (Go doesn't have support for casts anyway). It merely asks the runtime: "Does this value satisfy the given type?" There is no change in type. Now, let's take this further: It is generally agreed upon that duck typing differs from structural typing only in that it is evaluated dynamically instead of statically. Go's interface is quite clearly a structural type when evaluated statically. And what do you think the type assertion does in the example given? That's right: It performs a type assertion on a "structural type" at run time. Duck typing, by definition! > I don;t consider C a duck typing language too, because you can write ((Bird) ptr)->swim(), but perhaps you do?* No. First and foremost, where would the typing come into play? That will actually try to call the method, whether the pointed memory is suitable or not. There is no type checking to steer you around mistakenly calling something that shouldn't be called. Not at compile time, not at run time. It is literally called duck typing, not duck valuing. "Type" has significance. Where do you find it here?
- moritzwarhier 2y agoI have a stupid question (web dev, but also have used Java and C#). TypeScripts type system is commonly described as implementing "structural types" (not "duck" typed) And there are a ton of pragmatically sound gotchas around this, such as the importance of whether an object is used as an argument or a parameter, or if it is declared using an object literal. (focusing on objects here because for primitives I'd assume that TS has almost nominal typing) So, is there an ELI5 for the difference between structural typing and duck typing? I'd guess that duck typing is more similar to the callee perspective in TS (give me an object with the properties I need), while structural typing is more similar to the checks performed when initializing an object literal with a declared type? But I'm not sure if I'd be able to differentiate both terms succinctly. What is the relationship between duck typing and "type narrowing"? Or is that more of a "structural typing" thing?
- randomdata 2y ago> So, is there an ELI5 for the difference between structural typing and duck typing? While similar, structural typing is seen statically (think compile time), duck typing is seen dynamically (think run time).
- moritzwarhier 2y agoThanks, this makes sense, TS type narrowing only works with information known at compile-time (even when using runtime constructs for type narrowing). So I will go on to imagine duck-typing as the classic JS way where functions started with often pretty extensive runtime checks of their parameter values. I guess this also means that duck-typing is inherently tied to checking primitive types and/or object structures, return values etc at runtime.
- neonsunset 2y ago> So, is there an ELI5 for the difference between structural typing and duck typing? Likely just semantics. You could argue that the sliver of difference is just treating something like a particular API shape hence duck typing over structurally matching to an interface. For practical purposes however it does not matter. The runtime vs compile time argument is purely an implementation detail that has no relation to structural matching aka duck typing (heh) otherwise. In practice, I find this idea rather uncomfortable and C# has been avoiding it except for few very defined cases that are least likely to cause this confusion, like GetEnumerator and Enumerator.MoveNext+Current (it could be used as an enumerable in foreach loops but unless the type implements IEnumerable, you can't coerce it to the type). For the cases where specialization is needed, it is usually written as // could also be Handle<T> where T: IDataArg to avoid boxing for structs // as struct generics in .net are zero-cost via monomorphization void Handle(IDataArg arg) { if (arg is IPooledArg pooled) { var rented = arg.Rent(); // do something with the arg rented.Return(); } // slow path } No type confusion is possible as whatever is passed to the method has to declare it implements IDataArg. Same applies to 'arg' being 'IPooledArg' - it could have methods with names that would make it match the interface structurally but this is, quite literally, not a type-safe assumption. The authors may have explicitly decided not to expose it, or to provide explicit interface implementation that differs from pre-existing names. All this is very upfront and you won't be finding yourself having to rename methods or be surprised when your objects or structs are used in a way they are not supposed to because their triangle-shaped type happened to fit in a square-shaped interface hole.
- deleted 2y ago[deleted]
- simonz05 2y agoThis type of runtime type checking is quite common in Go. An example from bufio.Reader's WriteTo method: // WriteTo implements io.WriterTo. // This may make multiple calls to the [Reader.Read] method of the underlying [Reader]. // If the underlying reader supports the [Reader.WriteTo] method, // this calls the underlying [Reader.WriteTo] without buffering. func (b *Reader) WriteTo(w io.Writer) (n int64, err error) { b.lastByte = -1 b.lastRuneSize = -1 n, err = b.writeBuf(w) if err != nil { return } if r, ok := b.rd.(io.WriterTo); ok { m, err := r.WriteTo(w) n += m return n, err } if w, ok := w.(io.ReaderFrom); ok { m, err := w.ReadFrom(b.rd) n += m return n, err } if b.w-b.r < len(b.buf) { b.fill() // buffer not full } for b.r < b.w { // b.r < b.w => buffer is not empty m, err := b.writeBuf(w) n += m if err != nil { return n, err } b.fill() // buffer is empty } if b.err == io.EOF { b.err = nil } return n, b.readErr() }
- yegle 2y agoInterface smuggling: https://utcc.utoronto.ca/~cks/space/blog/programming/GoInterfaceSmuggling https://utcc.utoronto.ca/~cks/space/blog/programming/GoInter...
- glenjamin 2y agoThe Go standard library makes use of a number of “optional interfaces”, which it uses to detect when a type implements a higher level action in a more efficient or specific way This can be thought of as duck typing. Examples can be found here: https://blog.merovius.de/posts/2017-07-30-the-trouble-with-optional-interfaces/ https://blog.merovius.de/posts/2017-07-30-the-trouble-with-o...
- mseepgood 2y agoSorry, but where's the "horror"? I only see the description of a great feature.
- dilap 2y agoConfusing post; as I see it, it doesn't really have much to do with duck-typing. It's more an illustration that with Go you can, if you choose, take "any" as your argument type and then later cast to the actual type you need, risking, of course, run-time exceptions if the type is not fulfilled. Basically, you can opt-in to dynamic typing (the same as e.g. C#). If the method quack were quack(ducks ...Duck) then you'd get a compile-time error.
- randomdata 2y ago> It's more an illustration that with Go you can, if you choose, take "any" as your argument type and then later cast to the actual type you need, risking, of course, run-time exceptions if the type is not fulfilled. Not cast to just a concrete type, but to an interface. Literally duck typing. > then you'd get a compile-time error. Which is emblematic of structural typing, and the only real difference between structural typing and duck typing is that one is dealt with at compile time and the other at runtime. The article tells that Go supports both.
- Joker_vD 2y agoHow is that any different from doing public interface ISwim { void Swim(); } public interface IQuack { void Quack(); } public interface IDuck extends ISwim, IQuack { } public class Mallard implements IDuck { public void Swim() { System.out.println("mallard swimming"); } public void Quack() { System.out.println("mallard quacking"); } } public class Dog implements ISwim { public void Swim() { System.out.println("dog swimming"); } public void Bark() { System.out.println("dog barking"); } } public static void quack(Object... ducks) { for (Object duck: ducks) { ((ISwim)duck).Swim(); ((IQuack)duck).Quack(); } } public static void main() { quack(new Mallard(), new Dog()); } in Java? You can do this in Java, you know, casting down to an interface; the same goes for C#. Do those languages now have duck typing, just because in them you can up-cast anything to Object, and then try to down-cast to any other type, be it an interface or a class?
- 2y ago
- GrantMoyer 2y agoI think the Wikipedia article is simply wrong that duck typing is exclusive to dynamic type systems. Nominal typing means use of an object type checks if the explicitly named type of the object matches the explicitly named type the operation support (modulo some type inference). For example, C is nominally typed. Duck typing means that use of an object type checks if all operations on the object are defined, without that set of operations ever being explicitly defined. For example, C++ template substitution uses duck typing (pre-concepts). Finally, structural typing means that use of an object type checks if some explicitly specified set of operations on it are defined. For example C++20 templates with constraints use structural typing. Go interfaces seem to as well, although I'm not familiar enough with Go to know if that's exactly true.
- iamcreasy 2y ago> structural typing means that use of an object type checks if some explicitly specified set of operations on it are defined Can you please share an example? Structural typing[1] sounds like a subset/special case of Duck typing. [1] https://www.typescriptlang.org/docs/handbook/type-compatibility.html https://www.typescriptlang.org/docs/handbook/type-compatibil...
- seanmcdirmid 2y agoStructural subtyping is used in most ML-ish languages, including F# and Haskell.
- GrantMoyer 2y agoI was mistaken in the prior version of my comment when I said Crystal uses structural typing. As a somewhat trivial C++20 example though: template<typename T> concept CanDouble = requires(T t) {t + t; t * 2;}; template<CanDouble F> auto foo(F t) {return t + t;} template<typename B> auto bar(B t) {return t + t;} As I see it, the foo template function uses structural typing, because the required set of properties of F are explicitly specified (in this case with name "CanDouble"). Two operations, t + t and t * 2, must be defined for F. On the other hand, bar uses duck typing, because B can be any type that can be added to itself. Note that in this example, foo(std::string{"abc"}) will not compile, because string doesn't satisfy all the properties of CanDouble, even though the property it doesn't satisfy isn't actually used by foo. In other words, strings don't have the structure described by CanDouble. However, bar(std::string{"abc"}) does compile, because strings can be added to strings in C++, and B is only restricted by how it's used in bar. In other words strings "walk like a duck", so they're a duck.
- karmakaze 2y agoIt's no surprise. The example is ignoring the error from casting. It should be: if quacker, ok := duck.(interface { Quack() }); ok { quacker.Quack() } Ignoring errors leads to unexpected results. Failing to mention that it's purposely ignoring an error for a fun blog post is the opposite of informative.
- 38 2y agothat an who the fuck uses interface literals? I do Go personally and professionally for years and never seen it.
- didip 2y agoI was about to say, after so many years doing Go, I have never seen this and would love to read blog post about why interface literal is useful.
- mseepgood 2y agoYou can learn from the Go codebase to get a feel of why this is useful: https://github.com/golang/go/blob/master/src/cmd/go/internal/modfetch/repo.go#L394 https://github.com/golang/go/blob/master/src/cmd/go/internal... https://github.com/golang/go/blob/master/src/io/fs/fs.go#L262 https://github.com/golang/go/blob/master/src/io/fs/fs.go#L26... https://github.com/golang/go/blob/master/src/errors/wrap.go#L18 https://github.com/golang/go/blob/master/src/errors/wrap.go#... https://github.com/golang/go/blob/master/src/go/parser/resolver.go#L49 https://github.com/golang/go/blob/master/src/go/parser/resol...
- metadat 2y agoIf the interface check fails, does the code panic or does the `ok' value just get set to false? If `ok' gets set to false, that seems optimal. Pretty neat, in fact, what other language permits such low-key, easy runtime interface checks?
- 2y ago