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

后端 未结 16 2040

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:11

    dynamically typed language helps to quickly prototype algorithm concepts without the overhead of about thinking what variable types need to be used (which is a necessity in statically typed language).

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-22 02:14

    Statically Typed

    The types are checked before run-time so mistakes can be caught earlier.

    Examples = c++

    Dynamically Typed

    The types are checked during execution.

    Examples = Python

    0 讨论(0)
  • 2020-11-22 02:17

    Statically typed languages type-check at compile time and the type can NOT change. (Don't get cute with type-casting comments, a new variable/reference is created).

    Dynamically typed languages type-check at run-time and the type of an variable CAN be changed at run-time.

    0 讨论(0)
提交回复
热议问题