通过例子学习Rust

5.3 推断

Rust的类型推导系统非常智能。不仅能根据初始化语句里的右值推导类型,还能根据后续使用推导类型。下面是典型的例子:

fn main() { // Using local inference, 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); }

不强求明确声明变量的类型。编译器通常能自动推导出来。程序员也省事。