类型推断
类型推断引擎非常智能。它不仅查看初始化期间值表达式的类型,还会查看变量在初始化后的使用方式来推断其类型。以下是一个类型推断的高级示例。
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<u8>`) // TODO ^ Try commenting out the `vec.push(elem)` line println!("{:?}", vec); }
无需对变量进行类型标注,编译器和程序员都很开心!