Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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 of i32 numbers it will know that i32 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