Sub topic 7
Slicing strings and why s[0] does not compile
This chapter assumes you know basic Rust syntax, ownership and borrowing, and Option. It builds on the earlier chapters about &str, String, and UTF-8.
Why integer indexing is rejected
A Rust string is a sequence of UTF-8 bytes. Each character takes one to four bytes. Because of this, s[0] has no single sensible meaning. It could mean the first byte, which may be half a character, or the first character, which would require scanning. Indexing is expected to be constant time, and neither meaning fits that expectation. Rust refuses to choose, so this code fails to compile:
fn main() {
let s = String::from("héllo");
let c = s[0];
println!("{c}");
}The compiler reports that the type String cannot be indexed by {integer}.
Slicing with byte ranges
You can slice with a range. The offsets are measured in bytes, not characters.
fn main() {
let s = "héllo";
println!("{}", &s[0..1]);
println!("{}", &s[1..3]);
println!("{:?}", s.get(0..2));
}This prints h, then é, then None. The letter é occupies bytes 1 and 2. The range 1..3 covers it exactly. The range 0..2 ends in the middle of é, so get returns None.
Valid boundaries are offsets 0, 1, 3, 4, 5, and 6. Offset 2 is inside é.
Panic or Option
The two slicing forms differ in how they fail.
| Form | On a bad range | Use when |
|---|---|---|
| `&s[a..b]` | Panics | The offsets come from your own trusted code |
| `s.get(a..b)` | Returns `None` | The offsets come from outside input |
The panic happens at runtime, not at compile time. A slice also panics if the range runs past the end of the string.
Finding safe boundaries
Several tools help you avoid guessing:
s.is_char_boundary(i)returnstrueifiis a valid slice position.s.char_indices()yields each character together with its starting byte offset.s.find(...)returns a byte offset that is always a valid boundary.
The next program cuts a string after its first N characters by using char_indices:
fn first_chars(s: &str, n: usize) -> &str {
match s.char_indices().nth(n) {
Some((byte_index, _)) => &s[..byte_index],
None => s,
}
}
fn main() {
let s = "héllo wörld";
println!("{}", first_chars(s, 3));
println!("{}", first_chars(s, 100));
}It prints hél and then the whole string. The call to nth(n) finds the start of character number n, and that offset is a safe place to stop. If the string has fewer than n + 1 characters, nth returns None and the function returns the whole input.
Getting a single character
To read the character at a given position, go through chars():
fn main() {
let s = "héllo";
println!("{:?}", s.chars().nth(1));
println!("{:?}", s.chars().nth(10));
}This prints Some('é') and None. The cost is linear, because Rust must walk the string from the start. That cost is the reason the language does not hide this operation behind [].
Common errors
- Treating
len()as a character count. It returns bytes. - Slicing user input at a fixed offset, such as the first 10 bytes for a preview. Text with non-ASCII characters can panic.
- Expecting
chars()to match what a reader sees as one character. Some visible characters are severalcharvalues combined. The next chapter covers this.
Exercise
A function receives a &str named name from user input and must return its first 4 bytes as a preview. Which call is safe for any input, and what does it return for "añb" when asked for 0..2?
Show answer
Use name.get(0..4), which returns None instead of panicking when offset 4 is not a boundary or is past the end. For "añb", ñ occupies bytes 1 and 2, so offset 2 is inside it and get(0..2) returns None.