home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

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

December 2023
Code
fn main() {
  let mut words = vec!["bravo", "charlie", "delta"];
  words.insert(0, "alfa");
  dbg!(words);
}
Results
[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.

═══ § ═══