Prepending to a Vec in Rust: What Are Your Options?
Rust’s Vec is a powerful and flexible collection type. It’s fast at pushing and popping at the end , but sometimes you need to add an element to the front . That’s where things get tricky: Vec is backed by a contiguous array, so prepending requires shifting or reallocating elements. There’s no O(1) way to do this. In this post, we’ll walk through several ways to prepend to a Vec , compare their mechanics, and discuss when each is appropriate. The Problem You have a vector: let mut digits = vec![2, 3, 4]; You want to add 1 to the head , so that the result is [1, 2, 3, 4] . Option 1: Using insert(0, value) The simplest and most idiomatic solution: digits.insert(0, 1); Shifts all elements one place to the right. Uses ptr::copy under the hood (a single memmove ). Complexity: O(n) . This is usually the best choice unless you need to squeeze out every last cycle. Option 2: Build a New Vec With Capacity If you’re fine creating a new vector: let mut result = Vec::wi...