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 for strings

  • This is the same example as before, but this time we push a string first.
fn main() {
    let mut names = vec![];
    println!("{:?}", names);

    names.push(String::from("apple"));
    // names.push(23);   // error[E0308]: mismatched types - expected `&str`, found integer
    // names.push(3.14); // error[E0308]: mismatched types - expected `&str`, found floating-point number

    names.push(String::from("banana"));

    println!("{:?}", names);
    for name in names {
        println!("{}", name);
    }
}
[]
["apple", "banana"]
apple
banana