What is the difference between statically typed and dynamically typed languages?

后端 未结 16 2334

I hear a lot that new programming languages are dynamically typed but what does it actually mean when we say a language is dynamically typed vs. statically typed?

16条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 02:12

    Here is an example contrasting how Python (dynamically typed) and Go (statically typed) handle a type error:

    def silly(a):
        if a > 0:
            print 'Hi'
        else:
            print 5 + '3'
    

    Python does type checking at run time, and therefore:

    silly(2)
    

    Runs perfectly fine, and produces the expected output Hi. Error is only raised if the problematic line is hit:

    silly(-1)
    

    Produces

    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    

    because the relevant line was actually executed.

    Go on the other hand does type-checking at compile time:

    package main
    
    import ("fmt"
    )
    
    func silly(a int) {
        if (a > 0) {
            fmt.Println("Hi")
        } else {
            fmt.Println("3" + 5)
        }
    }
    
    func main() {
        silly(2)
    }
    

    The above will not compile, with the following error:

    invalid operation: "3" + 5 (mismatched types string and int)
    

提交回复
热议问题