I'm new to Rust. I understand that Rust predicts the type of bindings at compile time. The below code compiles and runs.
fn main() {
let mut numbers = Vec::new();
numbers.push(1);
}
What is the default type of the numbers vector?
Vec::new() relies on its context for information. When you push something to the vector, the compiler knows "oh, this is the kind of object I should be expecting". But since your example is pushing the integer literal 1, this appears to be related to the default type of an integer literal.
In Rust, an untyped integer literal will be assigned a value at compile time according to the context. For example:
let a = 1u8;
let b = 2;
let c = a + b;
b and c will be u8s; a + b assigns b to be the same type as a, and the output of the operation is a u8 as a result.
If no type is specified, the compiler appears to pick i32 (per this playground experiment). So in your specific example, and as seen in the playground, numbers would be a Vec<i32>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With