Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

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

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.