是安全键入还是静态键入? [英] Type Safe vs Static Typing?
问题描述
如果一种语言是类型安全的,那是否意味着您可以自动假定它是静态类型的,因为您必须在编译时检查类型?
例如,C是静态类型的而不是安全的,而Haskell是静态类型的并且是安全的.大多数(全部?)动态类型化的语言都是类型安全的,因为它们可以在运行时检查类型,以确保它们是正确的.此外,这些语言假定,由于您选择承受包括运行时类型信息的性能损失,因此您将希望尽可能有效地使用该信息,因此通常不允许将大块内存解释为错误的类型. /p>
动态类型化语言还有一种额外的类型安全度量,即强制.例如,如果您在javascript中键入[] + []
,它将看到+
的操作数是数组,不能直接添加,因此会将它们都转换为字符串,从而得到""
的结果(空字符串).
某些语言(例如javascript)通常会将其他内容强制转换为字符串,而PHP例如 reinterpret_cast
运算符,这意味着即使不进行任何转换,也可以将其转换为其他任何内容"这样做是没有道理的."例如,
float a = 6.2;
int b = reinterpret_cast<int>(a);
//b now contains some form of garbage
有关类型安全性的更完整说明,请参见此答案.
If a language is type-safe does that mean one could automatically assume that its statically typed since you would have to check types at compile time ?
C, for example, is statically typed and not type safe, while Haskell is statically typed and type safe. Most (all?) dynamically typed languages are type safe, as they have means of checking types at runtime to make sure they're the right thing. Additionally, these languages assume that because you have chosen to incur the performance penalty of including runtime type information, you would want to use that information as effectively as possible, and so generally do not allow interpreting a chunk of memory as the wrong type.
Dynamically typed languages have an additional measure of type safety, which is coercion. For example, if you type [] + []
in javascript, it will see that the operands to +
are arrays and cannot be added directly, and so will convert them both to strings, giving the result of ""
(the empty string).
Some languages, like javascript, will usually coerce other things to strings, while PHP for example will coerce strings to numbers to compare them.
EDIT: Type safety means not being allowed to interpret a chunk of memory holding something of type A as something of type B. As an example of type unsafety, C++ has the reinterpret_cast
operator, which means "convert anything to anything else even if it doesn't make sense to do so." For example,
float a = 6.2;
int b = reinterpret_cast<int>(a);
//b now contains some form of garbage
For a much more complete explanation of type safety, see this answer.
这篇关于是安全键入还是静态键入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!