Confronting Complexity in Rust Collections
Take a look at this block of Rust code:
let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0];
v.push(6);
println!("The first element is: {first}");
It won’t compile because of the way vectors work under the hood. The values of a vector are placed next to each other in memory. Pushing a new element onto the end of the vector may require allocating new memory for all elements to fit together contiguously. If this were the case, first would point to deallocated memory. Not ideal. The rules of borrowing prevent that from happening:
Aporiae – What Makes Rust Safe?
Here’s another block:
let s1 = String::from("hi");
let h = s1[0];
This code won’t compile either. Why should that be the case? String indexing is a common operation in most programming languages. But the truth, often hidden from view, is that strings are complicated – no matter how you slice them. It is unclear what value h should hold. A byte? A scalar value? A grapheme cluster? Better to not compile at all:
Common Collections - The Rust Programming Language
Do you see the pattern? Rust makes you confront complexity. You’ve seen two examples here: how vectors are stored in memory and how the representation of strings can be ambiguous. You cannot get away with computing as a concept. You’ve got to get your keyboard dirty and wrestle with the limitations of a real, physical machine:
Starting Systems Programming, Pt 1: Programmers Write Programs