Duck typing, must it be dynamic?

后端 未结 8 1123
花落未央
花落未央 2020-12-13 09:55

Wikipedia used to say* about duck-typing:

In computer programming with object-oriented programming languages, duck typing is a style of dynamic

8条回答
  •  时光取名叫无心
    2020-12-13 10:34

    There are situations in which dynamic duck typing and the similar static-typed code (in i.e. C++) behave differently:

    template 
    void foo(T& obj) {
        if(obj.isAlive()) {
            obj.quak();
        }
    }
    

    In C++, the object must have both the isAlive and quak methods for the code to compile; for the equivalent code in dynamically typed languages, the object only needs to have the quak method if isAlive() returns true. I interpret this as a difference between structure (structural typing) and behavior (duck typing).

    (However, I reached this interpretation by taking Wikipedia's "duck-typing must be dynamic" at face value and trying to make it make sense. The alternate interpretation that implicit structural typing is duck typing is also coherent.)

提交回复
热议问题