Rust類型轉換-推導

Rust類型轉換-推導

類型推理引擎是非常靈巧的。 它在一個初始化期間會尋找 r-value 的類型。 它也着眼於如何使用變量,事後推斷其類型。這裏是類型推斷的高級示例:

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);

}

需要的變量沒有類型註釋。