3 ms·
yes, with structural typing, you have to be able to do everything a duck can do, not just the duckish things you're interested in locally. In duck typing, if a
by zemo 14y ago
yes, with structural typing, you have to be able to do everything a duck can do, not just the duckish things you're interested in locally. In duck typing, if all you're interested in is walk_like_a_duck, anything with walk_like_a_duck is acceptable, even something that doesn't talk_like_a_duck, because in reality, you never defined the "duck" type to begin with; the actual "duck" type doesn't even exist. In structural typing, "duck" would be a concrete type. "duck typing" is a pretty shitty name for it, to be honest, because of that saying "if it walks like a duck and talks like a duck, it's a duck", but the reality is it's more like "if I need something that walks_like_a_duck and this walks_like_a_duck then it's good enough for me".
let's put it in another perspective: if you have a function that takes disparate types, then the thing that's passed in that function may be of arbitrary type. It's unknown at compile time how much memory will be allocated for the instantiation of that function in order to accept the parameter, because the type that's being passed it is unknown. In structural typing, like in Go, you know at compile time the type of the thing being passed in, and therefore, the amount of resources that will be required upon calling.
Or in another sense, an array of an interface value in Go has a well-defined memory layout, whereas an array of disparate types in a dynamic language does not have a well-defined memory layout at compile time.
internally, an interface value in Go is a two-tuple; it's an actual additional structure; it boxes the structure we're interested in. With duck typing, there is no box.
so yes, it's actually very different. The difference is more meaningful than people generally let on.