FAQ - Help and questions

What is the difference between an array, a Vec and a slice in Rust?

#collections#basics#slicespublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

An array has a fixed length that is part of its type. A Vec is a growable list stored on the heap. A slice, written &[T], is a borrowed window onto part of an array or Vec. Functions that only read a sequence should take &[T], because it accepts all three.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Use a Vec<T> when the number of items is not known until the program runs or changes. Use an array [T; N] when the length is a fixed fact, such as 12 months. Use &[T] for parameters: it is a pointer and a length, and borrowing it copies nothing.

src/main.rsrust
fn sum(values: &[i32]) -> i32 {
    values.iter().sum()
}

fn main() {
    let array: [i32; 3] = [1, 2, 3]; // fixed length, part of the type
    let mut vec: Vec<i32> = vec![1, 2, 3]; // growable, on the heap
    vec.push(4);

    let slice: &[i32] = &vec[1..3]; // a borrowed window onto either

    println!("{} {} {}", sum(&array), sum(&vec), sum(slice));
    println!("{array:?} {vec:?} {slice:?}");
    println!("{} {} {}", array.len(), vec.len(), slice.len());
}
text
6 10 5
[1, 2, 3] [1, 2, 3, 4] [2, 3]
3 4 2

Why it works#

&vec and &array convert to &[i32] automatically, so sum is written once and works with both. A slice made with &vec[1..3] holds items 1 and 2: the end is not included. Taking a slice while you still hold it prevents the original from being changed, which is the borrow checker protecting you from a Vec that moves its items when it grows.

Common mistakes#

  • Writing a parameter as &Vec<T>. Clippy warns about it (ptr_arg), and &[T] accepts more callers.
  • Indexing past the end. v[10] on a three-item list panics at run time. v.get(10) returns None instead.
  • Expecting let a = [0; 100_000_000] to be cheap. Arrays live where they are declared (usually the stack); big buffers belong in a Vec.

How do I make a Vec with a starting size?#

vec![0; 5] gives five zeros, and Vec::with_capacity(n) reserves room for n items without adding any.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet