Rust类型转换-推导

类型推理引擎是非常灵巧的。 它在一个初始化期间会寻找 r-value 的类型。 它也着眼于如何使用变量,事后推断其类型。这里是类型推断的高级示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fn main() {
// Because of the annotation, the compiler knows that `elem` has type u8.
let elem = 5u8;
// Create an empty vector (a growable array).
let mut vec = Vec::new();
// At this point the compiler doesn't know the exact type of `vec`, it
// just knows that it's a vector of something (`Vec<_>`).
// Insert `elem` in the vector.
vec.push(elem);
// Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec`)
// TODO ^ Try commenting out the `vec.push(elem)` line
println!("{:?}", vec);
}
需要的变量没有类型注释。

联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2024

备案号:京ICP备15003423号-3