Sub topic 5
String slices and UTF-8 boundaries
This chapter assumes you know basic Rust syntax, ownership, and how shared references borrow data. It also assumes you have seen the &[T] slice type and range syntax such as &a[1..4]. Here you will see how the same ideas apply to text, and why string slicing has a failure mode that array slicing does not.
What a `&str` is
A &str is a string slice. Like &[T], it is a borrowed view that stores a pointer and a length. Unlike &[T], the bytes it points to must always be valid UTF-8.
You meet &str in three common places:
- String literals such as
"hello"have type&'static str. The bytes live in the compiled program, so the borrow lasts for the whole run. - Slicing a
Stringwith a range, such as&s[0..5], gives a&strthat borrows from theString. - Passing
&Stringwhere a&stris expected works through deref coercion. The compiler converts the reference for you.
fn first_word(s: &str) -> &str {
match s.find(' ') {
Some(i) => &s[..i],
None => s,
}
}
fn main() {
let text = String::from("hello world");
println!("{}", first_word(&text));
println!("{}", first_word("single"));
}first_word takes &str, so it accepts both a &String and a literal. The returned slice borrows from the input. While that slice is alive, the borrow checker will not let you modify or clear text.
Offsets are bytes, not characters
The range in &s[a..b] counts bytes. It does not count characters. For plain ASCII text the two are the same, which hides the difference until you meet other text.
UTF-8 encodes each Unicode scalar value (a char in Rust) in one to four bytes.
| Bytes | Code point range | Example | Notes |
|---|---|---|---|
| 1 | U+0000 to U+007F | `a` | ASCII |
| 2 | U+0080 to U+07FF | `é` | Many accented Latin letters |
| 3 | U+0800 to U+FFFF | `€` | Most CJK characters |
| 4 | U+10000 to U+10FFFF | `😀` | Emoji and rare scripts |
Take the string "héllo". The letter é takes two bytes, so the string is six bytes long but has five characters.
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, then h and é. The range 1..3 covers both bytes of é.
The byte layout looks like this:
| Byte index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Content | `h` | `é` (first byte) | `é` (second byte) | `l` | `l` | `o` |
The valid places to cut are the start of the string, the end of the string, and the start of each character. Here those are 0, 1, 3, 4, 5, and 6. Index 2 falls in the middle of é, so it is not a valid cut.
What happens at a bad boundary
If either end of a range is not on a character boundary, slicing with [] panics at run time.
fn main() {
let s = "héllo";
let t = &s[0..2];
println!("{}", t);
}This program compiles. When it runs, it panics with a message like byte index 2 is not a char boundary; it is inside 'é' (bytes 1..3) of 'héllo'.
The panic exists because a &str must always hold valid UTF-8. Cutting é in half would produce a &str that breaks that rule. Rust stops you at the cut and does not let invalid text exist.
The compiler cannot see this problem. It depends on the data, so it shows up only when the program runs, often with input you did not test.
A range that goes past the end of the string panics too, with a different message. The rules for out-of-range access are the same as for arrays and vectors.
Checking before you cut
Rust gives you two tools that avoid the panic.
The first is str::get, which takes a range and returns an Option<&str>. It returns None for a range that is out of bounds or that cuts through a character.
fn main() {
let v = vec![1, 2, 3];
assert_eq!(v.get(5), None);
assert_eq!(v.get(1..5), None);
assert_eq!(v.get(1..), Some(&[2, 3][..]));
let s = "héllo";
assert_eq!(&s[0..1], "h");
assert_eq!(s.get(0..2), None); // byte 2 is inside the two-byte 'é'
assert_eq!(s.get(0..3), Some("hé"));
println!("all checks passed");
}The second is is_char_boundary, which tests one index.
fn main() {
let s = "héllo";
for i in 0..=s.len() {
println!("{} {}", i, s.is_char_boundary(i));
}
}Only index 2 prints false. Index 0 and index s.len() both count as boundaries, so an empty slice at either end is always valid.
Use get when the input comes from outside your program, such as user text, a file, or a network message. Use plain [] only when an earlier step has already guaranteed the offset is valid. A common example is an offset you got from find.
Getting safe offsets from the string itself
The most reliable way to get a valid offset is to ask the string for one. These methods always return offsets on character boundaries:
find,rfind, andmatch_indicesreturn the byte offset where a match starts.first_wordabove relies on this.char_indicesyields each character together with its starting byte offset.split_whitespace,split,lines, andtrimreturn&strslices without you computing any offsets.
fn main() {
let s = "héllo";
for (i, c) in s.char_indices() {
println!("{i}: {c} ({} bytes)", c.len_utf8());
}
}The output is 0: h (1 bytes), 1: é (2 bytes), 3: l (1 bytes), 4: l (1 bytes), and 5: o (1 bytes). The offsets skip from 1 to 3 because é takes two bytes.
Taking the first n characters
The standard library has no s[..n] for characters. You build it from char_indices.
fn take_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!("{}", take_chars(s, 3));
println!("{}", take_chars(s, 100));
}nth(n) finds the start of the character at position n. Everything before it is the first n characters. If the string has n or fewer characters, nth returns None and the whole string is returned. The first call prints hél. The second prints the full string.
This walks the string from the start, so it takes time proportional to n. Indexing an array by position is constant time. Finding the n-th character of a string is not. That is the cost of a variable-width encoding.
Truncating to a byte budget
Sometimes you have a limit in bytes, for example a database column or a protocol field. Then you want the longest valid prefix that fits. Walk the cut point back until it lands on a boundary.
fn truncate_bytes(s: &str, max: usize) -> &str {
if s.len() <= max {
return s;
}
let mut end = max;
while !s.is_char_boundary(end) {
end -= 1;
}
&s[..end]
}
fn main() {
println!("{}", truncate_bytes("héllo", 2));
println!("{}", truncate_bytes("héllo", 3));
println!("{}", truncate_bytes("héllo", 100));
}The output is h, hé, and héllo. The loop always ends because index 0 is always a boundary. Since a character is at most four bytes, the loop runs at most three times.
Choosing a method
The flowchart below summarizes how to pick a way to get part of a string.
Common errors
Indexing with a single integer
Writing s[0] on a String or &str does not compile. The compiler reports that the type str cannot be indexed by an integer. The reason is that Rust cannot decide what s[0] means. It could be the first byte, the first char, or the first visible character. It also cannot promise constant time for characters. You have to say which one you mean:
s.as_bytes()[0]gives the first byte as au8.s.chars().next()gives the firstcharas anOption<char>.&s[..1]gives a one-byte slice, which panics if the first character is wider than one byte.
Treating `len` as a character count
s.len() is the number of bytes. If you need the number of characters, use s.chars().count(). This also walks the string, so avoid it in a hot loop.
Assuming a `char` is what a user sees as one character
A char is a Unicode scalar value. Some visible characters are made of several scalar values. For example, é can be written as the single value U+00E9, or as e followed by a combining accent U+0301. The second form is two chars and three bytes, but it looks like one letter. Many emoji also combine several scalar values.
Slicing on char boundaries is always memory-safe and valid UTF-8, but it can still split what a reader sees as one character. The standard library does not handle these grapheme clusters. For that you need a crate such as unicode-segmentation.
Storing a slice and then changing the string
A &str slice of a String is a shared borrow. If you keep the slice and then call clear, push_str, or any other method that takes &mut self on the String, the compiler rejects the program. Growing a String may move its buffer, which would leave the slice pointing at freed memory. Finish with the slice, or copy it with to_string() or to_owned(), before you modify the original.
Mixing up the types of a slice
Slicing a String gives &str, not String. Writing let t: String = &s[0..3]; fails with a type mismatch. Call .to_string() if you need an owned copy, or keep the &str if you only need to read.
Summary of rules
- A
&stris a pointer and a byte length. Its contents are always valid UTF-8. - Range offsets are byte offsets. A cut must fall on a character boundary or the program panics.
- Use
getfor untrusted ranges,is_char_boundaryto test one index, andchar_indicesorfindto produce valid offsets. - There is no integer indexing for strings. Pick bytes or
chars on purpose. - Take
&strin function parameters. It accepts string literals and&String.
Exercise
Given let s = "a€b";, what is s.len()? Which of &s[1..4], &s[1..2], and s.get(1..2) succeed, and what does each return or do?
Show answer
The € character takes three bytes, so s.len() is 5 (1 + 3 + 1). &s[1..4] succeeds and returns "€", because byte 1 and byte 4 are both character boundaries. &s[1..2] panics because byte 2 is inside €. s.get(1..2) returns None instead of panicking.
Exercise
Write a function last_word(s: &str) -> &str that returns the part of the string after the last space, or the whole string if there is no space. Why is it safe to use [] slicing in your solution?
Show answer
Use rfind, then slice from the byte after the space. A space is one byte, so adding 1 lands on the next boundary.
fn last_word(s: &str) -> &str {
match s.rfind(' ') {
Some(i) => &s[i + 1..],
None => s,
}
}
Slicing with [] is safe here because rfind returns the start of a match, which is always a character boundary. The space is exactly one byte wide, so i + 1 is also a boundary, even when the words contain multi-byte characters.