Topic
Slices & Arrays
Arrays store a fixed number of same-type values with the size baked into the type at compile time. A slice is a borrowed window into part of an array — it has no size in its type, so one function can accept any length. Rust gives you direct indexing when you know a position is valid, and get() when it might not be.
Quick Reference
| Concept | What it means |
|---|---|
| Array | Fixed-size list where every element has the same type. Stored on the stack. |
| [T; N] | Array type signature: T is the element type, N is the count (must be known at compile time). |
| [value; count] | Short init syntax: create an array with count copies of value. |
| len() | Returns how many elements are in an array or slice. |
| Indexing | Access an element with [index]. First element is at 0. Out of bounds panics. |
| get() | Returns Option — safe way to access elements without panicking. |
| Slice (&[T]) | A borrowed view into a chunk of an array or collection. Type is &[T]. |
| enumerate() | Returns tuples of (index, value) when iterating over a collection. |
| Term | What it means | When you use it |
|---|---|---|
| Array | Fixed-size list where every element has the same type, stored on the stack | When you need a fixed number of same-type values known at compile time |
| [T; N] | Array type signature: T is the element type, N is the count | When declaring or annotating an array variable |
| [value; count] | Short init syntax: create an array with count copies of value | When all elements start with the same default value |
| len() | Returns how many elements are in an array or slice | When you need to know the size at runtime |
| Indexing | Access an element with [index]. First element is at 0. Out of bounds panics. | When you know the position is always valid |
| get() | Returns Option — safe way to access elements without panicking | When the position might be out of range |
| Slice &[T] | A borrowed view into a chunk of an array or collection | When passing part of a collection to a function |
| enumerate() | Returns tuples of (index, value) when iterating | When you need both the index and the value in a loop |