home ~ projects ~ socials

Add An Element To The Front Of A Rust Vec With .insert()

fn main() {
  let mut words = vec!["bravo", "charlie", "delta"];
  words.insert(0, "alfa");
  dbg!(words);
}
Output:
[neopolitan_code_run:4] words = [
    "alfa",
    "bravo",
    "charlie",
    "delta",
]

This is like "unshift" in other languages that pushing a new element onto the front of a Vec.

The first value passed to .insert() is the index position to put the new element. All the rest of the elements are shifted to the right. By using 0 the new element becomes the first one with the rest of the elements shifted down.

-- end of line --