12

What are the differences between the following three declarations?

let a = [1, 2, 3];
let b = &[1, 2, 3];
let c = vec![1, 2, 3];

I understand what vec![] does, but when should [] and &[] be used?

1

1 Answer 1

35

Although this is basic information you should find as soon as you start reading Rust docs or The Rust Book, here's some quick explanation:

  1. Array

let a = [1, 2, 3] is array of 3 elements that resides completely in the stack

stack:

+-----------+
| 1 | 2 | 3 |
+-----------+
  1. Slice

let b = &[1, 2, 3] is a reference to an array of 3 elements also in the stack:

         stack:
                 +-----------+
                 | 1 | 2 | 3 |
                 +-----------+
                 ^
         +---+   |
pointer: | * |---|
         +---+

If you change it to let b: &[u32] = &[1, 2, 3], b won't be just a reference to an array, but a slice because Rust will perform a Deref coercion. Slices are references that also store the length of what they point to (these kind of references are known as fat-pointers):

         stack:
                 +-----------+
                 | 1 | 2 | 3 |
                 +-----------+
                 ^
         +---+   |
pointer: | * |---|
         +---+
length:  | 3 |
         +---+
  1. Vec

let c = vec![1, 2, 3] is a dynamically allocated vector, that is, its data will reside in the heap in order to be able to change its size during runtime, but in the stack it will store the reference to the heap data, the length and the capacity of the vector:

            stack:       heap:
            +---+     +-----------+---+
pointer:    | * |---->| 1 | 2 | 3 |...|
            +---+     +-----------+---+
length:     | 3 |
            +---+
capacity:   | 4 |
            +---+
1
  • 1
    Hi, thanks for your nice explanation. I am reading the "Rust Programming Book". Most examples in that book used string slices. So, I forgot about what other kind of slice looked like. Still learning.
    – taiyebur
    Sep 9, 2019 at 5:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.