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 also assumes you have read the earlier chapter on UTF-8, where you saw that str is a sequence of bytes that must be valid UTF-8. Here you will use that fact to slice strings, and you will see why Rust refuses integer indexing.
What does not compile
Programmers coming from Python, JavaScript, or C often try this:
fn main() {
let s = String::from("hello");
let first = s[0];
println!("{first}");
}The compiler rejects it with an error like `the type str cannot be indexed by {integer} . The standard library implements Index for str and String with range types such as Range<usize> and RangeFrom<usize>. It does not implement it for a single usize`. This is a deliberate API decision with three reasons.
- A byte is not a character. A
stris stored as UTF-8, sos[0]could only mean "the first byte". For "hello" that happens to look like'h'. For "héllo" or any non-Latin text, a single byte is often half of a character and meaningless on its own. - "Element" has no single meaning. A string can be viewed as bytes, as
charvalues (Unicode scalar values), or as grapheme clusters (what a reader sees as one character). Picking one fors[i]would hide the other two. - Indexing is expected to be O(1). Finding the n-th
charrequires scanning from the start, because characters take 1 to 4 bytes. Rust does not want an innocent-lookings[i]inside a loop to turn the loop into O(n²).
Instead, Rust makes you say which unit you mean. Bytes use s.as_bytes()[i]. Characters use s.chars().nth(i). Substrings use a range, which is what the rest of this chapter covers.
Slicing with byte ranges
A range index on a string returns a &str, a borrowed view into part of the original bytes. No data is copied.
fn main() {
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..];
let start = &s[..2];
let all = &s[..];
let inclusive = &s[0..=4];
println!("{hello}|{world}|{start}|{all}|{inclusive}");
}This prints hello|world|he|hello world|hello. The range rules are the same as for slices of arrays:
- The start is inclusive and the end is exclusive, unless you write
..=. - Either bound may be omitted.
- The numbers are byte offsets, not character positions.
The result is a &str whose lifetime is tied to the original. While hello is alive, you cannot call s.clear() or s.push_str(...), because those need a mutable borrow. The borrow checker enforces this, which is the same guarantee that makes slices safe in other Rust code.
Char boundaries
Byte offsets are only valid at char boundaries: the positions where one encoded character ends and the next begins. In "héllo" the characters occupy these bytes:
| Character | h | é | l | l | o |
|---|---|---|---|---|---|
| Byte offsets | 0 | 1..3 | 3 | 4 | 5 |
| Bytes used | 1 | 2 | 1 | 1 | 1 |
The valid boundaries are 0, 1, 3, 4, 5, and 6 (the end). Offset 2 falls in the middle of é. Running the slices from the spine:
fn main() {
let s = "héllo";
println!("{}", &s[0..1]);
println!("{}", &s[1..3]);
println!("{:?}", s.get(0..2));
}The output is:
h
é
NoneIf the last line used &s[0..2] instead, the program would panic at runtime with a message like `byte index 2 is not a char boundary; it is inside 'é' (bytes 1..3) of héllo . A range that ends past s.len()` panics too, and so does a range whose start is greater than its end.
The following diagram shows how to choose a slicing approach.
Offsets you can trust
Direct slicing is safe when the offsets come from the string itself. Methods such as find, rfind, char_indices, and split_once return positions that are always on char boundaries.
fn main() {
let s = "größe=42";
if let Some(i) = s.find('=') {
let key = &s[..i];
let value = &s[i + 1..];
println!("{key} -> {value}");
}
}The i + 1 is safe here because '=' occupies exactly one byte. If the separator were a multi-byte character, you would add separator.len_utf8() instead. This is a common mistake. char::len_utf8 returns the number of bytes a character takes in UTF-8.
Checked slicing
When offsets come from outside the string, such as user input, a protocol field, or arithmetic, use the checked methods:
fn main() {
let s = "héllo";
println!("{:?}", s.get(0..1));
println!("{:?}", s.get(0..2));
println!("{:?}", s.get(10..12));
println!("{}", s.is_char_boundary(2));
println!("{}", s.is_char_boundary(3));
}This prints Some("h"), None, None, false, and true. get returns Option<&str>, with None for any invalid range, whether it is off a boundary, out of bounds, or reversed. is_char_boundary tests a single offset. split_at divides a string at a byte offset and panics on a bad one. The checked variant split_at_checked (stable since Rust 1.80) returns an Option instead.
Taking the first n characters
A common need is "the first n characters", for example to truncate text for display. Find the byte offset of the (n+1)-th character with char_indices, and slice there.
fn prefix_chars(s: &str, n: usize) -> &str {
match s.char_indices().nth(n) {
Some((i, _)) => &s[..i],
None => s,
}
}
fn main() {
println!("{}", prefix_chars("héllo", 2));
println!("{}", prefix_chars("héllo", 10));
println!("{}", prefix_chars("日本語のテキスト", 3));
}The output is hé, héllo, and 日本語. char_indices yields (byte_offset, char) pairs, so the offset it gives you is already a valid boundary. If the string has fewer than n + 1 characters, nth returns None and the whole string is returned. The function returns a &str that borrows from the input, so it does not allocate.
Note that "character" here means a char, a Unicode scalar value. A visible character such as é written as e plus a combining accent is two char values, and this function can cut between them. Handling that correctly requires grapheme segmentation, which the next chapter covers.
Choosing between the options
| Goal | Tool | Cost | Failure behavior |
|---|---|---|---|
| Slice at offsets from `find` or `char_indices` | `&s[a..b]` | O(1) | Cannot fail with these offsets |
| Slice at untrusted offsets | `s.get(a..b)` | O(1) | Returns `None` |
| Test one offset | `s.is_char_boundary(i)` | O(1) | Returns `false` |
| Get the *n*-th `char` | `s.chars().nth(n)` | O(n) | Returns `None` |
| Get the *n*-th byte | `s.as_bytes()[n]` | O(1) | Panics if out of bounds; the byte may be part of a character |
| First *n* characters | `char_indices().nth(n)` | O(n) | Returns the whole string if shorter |
Common mistakes
- Treating
len()as a character count.s.len()is the number of bytes. Using&s[..s.len() / 2]to cut a string in half can land inside a character. - Slicing user text at fixed offsets. Code such as
&name[..3]works for "Bob" and panics for "Éloïse" at some offsets. Usegetorprefix_chars. - Assuming one
charis one visible character. Combining marks and emoji sequences span severalcharvalues. - Reaching for
chars().collect::<Vec<char>>()just to index. This allocates four bytes per character. It is fine for a one-off algorithm that needs random access tocharvalues, but it is wasteful for a single lookup. - Forgetting the borrow. A slice keeps the original
Stringborrowed. If you need the text to outlive the original or to be modified independently, call.to_string()or.to_owned()on the slice.
Exercise
Given let s = "naïve café";, what does s.len() return, what does s.get(0..3) return, and what does &s[0..3] do? (ï and é each take 2 bytes in UTF-8, and a is at byte offset 1.)
Show answer
s.len() is 12: ten characters, with two of them taking 2 bytes each. The bytes are n (0), a (1), ï (2..4), v (4), e (5), space (6), c (7), a (8), f (9), é (10..12). Offset 3 is inside ï, so s.get(0..3) returns None and &s[0..3] panics with a "not a char boundary" message. s.get(0..4) would return Some("naï").
Exercise
Write a function suffix_chars(s: &str, n: usize) -> &str that returns the last n characters of s (or all of s if it has fewer than n characters) without panicking on any UTF-8 input.
Show answer
Use char_indices in reverse. fn suffix_chars(s: &str, n: usize) -> &str { if n == 0 { return ""; } match s.char_indices().rev().nth(n - 1) { Some((i, _)) => &s[i..], None => s } }. char_indices is double-ended, so rev() walks from the end. The nth(n - 1) call yields the start of the n-th character from the end, and its offset is a valid boundary. For n == 0 the function returns the empty string early, to avoid underflow on n - 1. For example, suffix_chars("héllo", 4) returns "éllo".