Mutable empty vector with type definition
-
vec!
-
push
-
We can also declare the type of the values in the vector. It might make the code more readable.
-
And it might eliminate the need to explicitely tell a
parsemethod the target value type. -
In this case Rust will see the
parsemethod and because the result is pushed onto a vector ofi32numbers it will know thati32is the type of the number variable.
fn main() {
let mut numbers: Vec<i8> = vec![];
println!("{:?}", numbers);
let input = "42";
// names.push(input);
// mismatched types
let number = input.parse().unwrap();
numbers.push(number);
println!("{:?}", numbers);
for num in numbers {
println!("{}", num);
}
}
[]
[42]
42