变量与赋值
All variables in a dynamically typed language are “variant”-like. This means that their type is not fixed, and is only modified through assignment. Example:
动态类型语言中的所有变量都是“可变”的。这意味着它们的类型不是固定的,而是通过赋值修改的。例如:
静态语言的:
int a; // Value uninitialized 变量没初始化
a = 5; // This is valid 合法
a = "Hi!"; // This is invalid 不合法
动态语言的:
var a # null by default 默认是空类型
a = 5 # Valid, 'a' becomes an integer 合法,a变成了整型
a = "Hi!" # Valid, 'a' changed to a string 合法,a改变成了字符串型
Functions are of dynamic nature too, which means they can be called with different arguments, for example:
函数参数
函数也是动态的,这意味着它们可以用不同类型的参数调用,比如:
静态语言的:
void print_value(int value) {
printf("value is %i\n", value);
}
[..]
print_value(55); // Valid
print_value("Hello"); // Invalid
动态语言的:
func print_value(value):
print(value)
[..]
print_value(55) # Valid
print_value("Hello") # Valid
指针与引用
In static languages, such as C or C++ (and to some extent Java and C#), there is a distinction between a variable and a pointer/reference to a variable. The latter allows the object to be modified by other functions by passing a reference to the original one.
在静态语言(如C或C++)(以及在Java和C#一定程度上),变量和指针/引用与变量之间存在区别。后者通过传递对原始函数的引用,允许其他函数修改对象。
In C# or Java, everything not a built-in type (int, float, sometimes String) is always a pointer or a reference. References are also garbage-collected automatically, which means they are erased when no longer used. Dynamically typed languages tend to use this memory model, too. Some Examples:
在C# 或Java中,不是内置类型(int,float,有时的String)的任何东西都是指针或引用。引用也是自动内存垃圾回收,这意味着它们在不再使用时被删除。动态类型的语言也倾向于使用这种内存模型。示例:
C++
void use_class(SomeClass *instance) {
instance->use();
}
void do_something() {
SomeClass *instance = new SomeClass; // Created as pointer
use_class(instance); // Passed as pointer
delete instance; // Otherwise it will leak memory
}
JAVA
@Override
public final void use_class(SomeClass instance) {
instance.use();
}
public final void do_something() {
SomeClass instance = new SomeClass(); // Created as reference
use_class(instance); // Passed as reference
// Garbage collector will get rid of it when not in
// use and freeze your game randomly for a second
}