Slices in Rust
Rust protects you from doing stupid things via an ingenious mechanism.
Slices allow us to select contiguous elements of a container via an immutable reference.
At least, I haven’t yet come across any mention of a step size in the Rust docs so I’m assuming they have to be contiguous.
Note that the end of the range is not included; in the following code we get elements at indices 1, 2 and 3, but not 4.
This code prints [1, 2, 3]
:
We can do the same thing with strings.
This code prints ‘worst’
:
Something really interesting happens if we use mutable strings. The following code works, and prints ‘best’
.
Since it’s a mutable string, we can clear it if we want, although here this has no effect since we’re not doing anything with it after clearing it.
If we try to clear it before printing ‘best’
via the reference, the code won’t compile. This would leave us with an invalid reference to part of a string that’s been cleared.
The way Rust helpfully stops us compiling this code is interesting. Here’s the error.
The slice is an immutable reference. To clear the string, clear()
needs to obtain a mutable reference, but here it can’t obtain one. You can’t have any other references to a value if you have a mutable reference to it, and here we’re still using the immutable reference.
I found it interesting that if I try to print something completely out of bounds, it compiles just fine, and panics at runtime.
I would have thought that if it knows the String length at compile time it would have a compile error...