Sub topic 5
String slices and UTF-8 boundaries
This chapter assumes you know ownership, basic borrowing, and the &[T] slice type from earlier chapters. It covers how &str follows the same idea as &[T], and why its indices are byte offsets, not character positions.
A &str is a slice of bytes
A &str is a borrowed view into UTF-8 encoded text. It is a pointer plus a length in bytes, like &[u8], with one extra guarantee: the bytes are always valid UTF-8. String literals have type &'static str. Borrowing part of a String also gives a &str.
UTF-8 stores each character in one to four bytes. ASCII characters take one byte. Many others take more. The word héllo shows this:
| Byte index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Character | h | é (first byte) | é (second byte) | l | l | o |
The string has 5 characters but 6 bytes. Range indices in &s[a..b] always count bytes.
fn main() {
let s = "héllo";
println!("bytes: {}", s.len());
println!("chars: {}", s.chars().count());
println!("{}", &s[0..1]);
println!("{}", &s[1..3]);
}This prints bytes: 6, chars: 5, h, and é. The range 1..3 covers both bytes of é.
Character boundaries
A range is valid only if both ends fall on a character boundary. A boundary is the start of a character or the end of the string. Index 2 in héllo sits in the middle of é, so it is not a boundary.
Slicing at a non-boundary panics at run time:
fn main() {
let s = "héllo";
let part = &s[0..2]; // panics: byte index 2 is not a char boundary
println!("{}", part);
}The compiler cannot catch this, because the check depends on the data. A literal index into a literal string still compiles. Rust cannot reject it ahead of time.
Checking boundaries without panicking
As with [T], the get method returns an Option instead of panicking. is_char_boundary tests one index, and char_indices yields each character together with its starting byte offset.
fn main() {
let s = "héllo";
assert!(s.is_char_boundary(1));
assert!(!s.is_char_boundary(2));
assert_eq!(s.get(0..2), None);
assert_eq!(s.get(1..3), Some("é"));
for (i, c) in s.char_indices() {
println!("{i}: {c}");
}
}The loop prints offsets 0, 1, 3, 4, and 5. Offset 2 is skipped because it is inside é.
Slicing by character count
You cannot index a &str by character position, so s[2] does not compile. If you need the first n characters, use char_indices to find the byte offset of character n, then slice there.
fn prefix_chars(s: &str, n: usize) -> &str {
match s.char_indices().nth(n) {
Some((i, _)) => &s[..i],
None => s,
}
}
fn main() {
let s = "héllo wörld";
println!("{}", prefix_chars(s, 3));
println!("{}", prefix_chars(s, 50));
}This prints hél and then the whole string. The offset comes from the iterator, so it is always a boundary and the slice cannot panic. The function walks the string from the start, so it takes time proportional to n.
Be careful about what "character" means. chars() yields Unicode scalar values. Some things a reader sees as one character, such as a letter with a combining accent, are several scalar values. Splitting between them is legal but can look wrong. Handling that fully needs a crate that implements Unicode grapheme segmentation.
Common errors
- Using
len()as a character count. It returns bytes. Uses.chars().count()for scalar values. - Slicing at a computed offset. Offsets from arithmetic may land inside a character. Take offsets from
find,char_indices, oris_char_boundaryinstead. - Expecting
&strto be mutable. A&stris read-only. To change text, own it in aString. - Holding a slice while changing the
String. A&strborrowed from aStringkeeps it borrowed. Callingclear()orpush_strwhile the slice is alive is a compile error.
Exercise
Given let s = "naïve";, what are s.len() and s.chars().count()? Which of s.get(0..3) and s.get(0..4) returns None? (ï is two bytes in UTF-8.)
Show answer
s.len() is 6 and s.chars().count() is 5. The bytes are n (0), a (1), ï (2 and 3), v (4), e (5). Index 3 is inside ï, so s.get(0..3) returns None. Index 4 is a boundary, so s.get(0..4) returns Some("naï").