Consider this example:
fn main() {
let v: Vec<i32> = vec![1, 2, 3, 4, 5];
let b: i32 = (&v[2]) * 4.0;
println!("product of third value with 4 is {}", b);
}
Run Code Online (Sandbox Code Playgroud)
This fails as expected as float
can't be multiplied with &i32
.
error[E0277]: cannot multiply `{float}` to `&i32`
--> src\main.rs:3:23
|
3 | let b: i32 = (&v[2]) * 4.0;
| ^ no implementation for `&i32 * {float}`
|
= help: the trait `std::ops::Mul<{float}>` is not implemented for `&i32`
Run Code Online (Sandbox Code Playgroud)
But when I change the float to int, it works fine.
fn main() {
let v: Vec<i32> = vec![1, 2, 3, 4, 5];
let b: i32 = (&v[2]) * 4;
println!("product of third value with 4 is {}", b);
}
Run Code Online (Sandbox Code Playgroud)
Did the compiler implement the operation between &i32
and i32
?
If yes, how is this operation justified in such a type safe language?
Luk*_*odt 10
编译器是否实现了
&i32
和之间的操作i32
?
是。好吧,不是编译器,而是标准库。您可以在文档中看到impl 。
如果是,如何用这种类型安全的语言来证明此操作的合理性?
“类型安全”不是布尔属性,而是频谱。大多数C ++程序员会说C ++是类型安全的。但是,C ++具有许多可在类型之间自动转换的功能(构造函数,operator T
引用值等等)。在设计编程语言时,必须权衡错误的风险(引入方便的类型转换时)与不便(如果没有缺陷时)。
举一个极端的例子:考虑是否Option<T>
会取消引用,T
如果出现这种情况则恐慌None
。这是大多数具有的语言的行为null
。我认为很明显,这种“功能”导致了现实世界中的许多错误(搜索术语“十亿美元的错误”)。另一方面,让我们考虑一下&i32 * i32
编译可能导致哪些错误。老实说我没有想到。Maaaybe有人想将一个值的原始指针与整数相乘?在Rust中不太可能。因此,由于引入带有此功能的错误的机会很小,但是很方便,因此决定实施该功能。
这始终是设计师必须平衡的东西。在此频谱上,不同的语言处于不同的位置。Rust可能被认为比C ++更具“类型安全”,但毫无疑问,甚至还有比Rust更“类型安全”的语言。在这种情况下,“更安全的类型”仅表示:决策更倾向于“不便而不是潜在的错误”。
归档时间: |
|
查看次数: |
123 次 |
最近记录: |