Mutable empty vector for numbers (push)
-
push
-
mut
-
vec!
-
We can also create a mutable empty vector without even declaring the types of the values.
-
When we
push
the first value that's how Rust will know what is the type of the elements of the vector. -
Trying to push values of other types would then generate a compilation error.
fn main() { let mut names = vec![]; println!("{:?}", names); names.push(23); // names.push("hello"); // error[E0308]: mismatched types - expected integer, found `&str` // names.push(3.14); // error[E0308]: mismatched types - expected integer, found floating-point number names.push(19); println!("{:?}", names); for name in names { println!("{}", name); } }
[]
[23, 19]
23
19