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
parse
method the target value type. -
In this case Rust will see the
parse
method and because the result is pushed onto a vector ofi32
numbers it will know thati32
is 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