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?
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 u8
s; 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>
.
Vectors in Rust are generic, which means that they don't have a default type - unless by default you mean Vec<T>
(T
is a generic type parameter) or Vec<_>
(_
is a type placeholder).
If the compiler doesn't find any related type annotation or isn't able to infer the element type using type inference, it will refuse to build the code:
let mut numbers = Vec::new();
error[E0282]: type annotations needed
--> src/main.rs:2:23
|
2 | let mut numbers = Vec::new();
| ----------- ^^^^^^^^ cannot infer type for `T`
| |
| consider giving `numbers` a type
You can verify it further by trying to use a trick to find out the type of a variable:
let mut numbers = Vec::new();
let () = numbers;
error[E0308]: mismatched types
--> src/main.rs:4:9
|
3 | let () = numbers;
| ^^ expected struct `std::vec::Vec`, found ()
|
= note: expected type `std::vec::Vec<_>` // Vec<_>
found type `()`