Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between [], &[], and vec![]?

Tags:

rust

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?

like image 245
taiyebur Avatar asked Sep 09 '19 05:09

taiyebur


1 Answers

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 |
            +---+
like image 92
Anler Avatar answered Oct 11 '22 13:10

Anler