Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default type of `Vec::new()` in rust?

Tags:

vector

rust

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?

like image 792
Rajkumar Natarajan Avatar asked Nov 30 '22 21:11

Rajkumar Natarajan


1 Answers

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>.

like image 78
MutantOctopus Avatar answered Dec 04 '22 14:12

MutantOctopus