What is the difference between statically typed and dynamically typed languages?
我听到很多新的编程语言是动态类型的,但当我们说一种语言是动态类型还是静态类型时,它实际上意味着什么?
Statically typed languages
A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is (eg: Java, C, C++); other languages offer some form of type inference, the capability of the type system to deduce the type of a variable (eg: OCaml, Haskell, Scala, Kotlin)
The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage.
Dynamically typed languages
A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with type inference). Example: Perl, Ruby, Python
Most scripting languages have this feature as there is no compiler to do static type-checking anyway, but you may find yourself searching for a bug that is due to the interpreter misinterpreting the type of a variable. Luckily, scripts tend to be small so bugs have not so many places to hide.
Most dynamically typed languages do allow you to provide type information, but do not require it. One language that is currently being developed, Rascal, takes a hybrid approach allowing dynamic typing within functions but enforcing static typing for the function signature.
Statically typed programming languages do type checking (the process of verifying and enforcing the constraints of types) at compile-time as opposed to run-time.
Dynamically typed programming languages do type checking at run-time as opposed to Compile-time.
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)
链接地址: http://www.djcxy.com/p/12538.html
上一篇: 编译的语言可以具有什么样的解释语言功能?
下一篇: 静态类型语言和动态类型语言有什么区别?