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?
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:
let a = [1, 2, 3]
is array of 3 elements that resides completely in the stack
stack:
+-----------+
| 1 | 2 | 3 |
+-----------+
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 |
+---+
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 |
+---+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With