Blog

Part 5 · Strings in Rust: String, &str and Why s[0] Doesn’t Compile

Rust has two string types, String and &str, and both hold UTF-8 bytes. This part shows why len counts bytes, why s[0] doesn’t compile, how slicing can panic, and the string methods you’ll use every day.

Rust has two string types you’ll meet on day one: String and &str. Both hold text as UTF-8 bytes. That one fact explains most of the surprises in this part: why .len() gives a number you didn’t expect, why s[0] doesn’t compile, and why a slice can crash your program.

This part covers the two types, bytes and characters, slicing, building strings, and the methods you’ll use most. It builds on the slices from Part 4. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

Both words have five letters. Decide what this prints before you scroll down:

fn main() {
    let plain = "hello";
    let accent = "héllo";
    println!("{} {}", plain.len(), accent.len());
}

It prints:

5 6

“héllo” has five letters, but .len() says 6. That isn’t a bug. In Rust, .len() on a string counts bytes, not letters. Most English letters take one byte. The é takes two. The rest of this part follows from that.

Two string types

Here are both types side by side:

fn main() {
    let greeting: &str = "hello";
    let mut name: String = String::from("Ana");
    name.push_str(" Silva");
    println!("{greeting}, {name}");
    println!("String: {} bytes", std::mem::size_of::<String>());
    println!("&str:   {} bytes", std::mem::size_of::<&str>());
}

It prints:

hello, Ana Silva
String: 24 bytes
&str:   16 bytes

A String owns its text. The text lives in a buffer on the heap, and the String can make that buffer bigger. That’s why name can take push_str. On a 64-bit machine, the String itself is 24 bytes: a pointer to the buffer, the length, and the capacity. Part 6 shows what a String looks like in memory.

A &str (say “string slice”) owns nothing. It’s a view of text that lives somewhere else. On a 64-bit machine it’s 16 bytes: a pointer to the first byte, and a length. That’s the same shape as the array slices in Part 4, and the same idea. A &str is a slice of UTF-8 bytes.

You can’t grow a &str. It only looks at text that something else holds.

Where string literals live

A string literal like "hello" is a &str. Its bytes are stored inside your compiled program, next to the machine code. They’re there from the moment the program starts until it ends.

The full type of a literal is &'static str. The 'static means “this view is good for the whole run of the program”. Part 9 explains names that start with '. For now, read &'static str as “a piece of fixed text baked into the program”.

Getting one from the other

You’ll switch between the two types all the time:

fn main() {
    let owned: String = String::from("hello");
    let also_owned: String = "hello".to_string();
    let view: &str = &owned;
    let part: &str = &owned[1..4];
    println!("{owned} {also_owned} {view} {part}");
}

It prints:

hello hello hello ell
  • String::from("...") and "...".to_string() both copy the text into a new heap buffer that you own.
  • &owned gives you a &str view of the whole String. Part 7 covers what the & means. For now, read it as “let me look at this”.
  • &owned[1..4] is a view of bytes 1, 2 and 3. It’s the same range syntax as array slices.

A function that only reads text should take a &str. Then it accepts a literal and a String alike:

fn shout(text: &str) -> String {
    text.to_uppercase()
}

fn main() {
    let name = String::from("ana");
    println!("{}", shout("hello"));
    println!("{}", shout(&name));
    println!("{name} is still here");
}

It prints:

HELLO
ANA
ana is still here

UTF-8: one character, one to four bytes

Every String and every &str holds UTF-8. UTF-8 is a way of writing any character from any language as bytes:

  • the 128 ASCII characters (English letters, digits, common punctuation) take 1 byte each;
  • letters like é, ñ and ü take 2 bytes;
  • most Chinese, Japanese and Korean characters take 3 bytes;
  • most emoji take 4 bytes.

Rust lets you look at the same text as bytes or as characters:

fn main() {
    let word = "héllo";
    println!("len:           {}", word.len());
    println!("chars().count: {}", word.chars().count());
    println!("bytes:         {:?}", word.as_bytes());
    for (i, c) in word.char_indices() {
        println!("byte {i}: {c} takes {} byte(s)", c.len_utf8());
    }
}

It prints:

len:           6
chars().count: 5
bytes:         [104, 195, 169, 108, 108, 111]
byte 0: h takes 1 byte(s)
byte 1: é takes 2 byte(s)
byte 3: l takes 1 byte(s)
byte 4: l takes 1 byte(s)
byte 5: o takes 1 byte(s)
  • .len() is the number of bytes: 6.
  • .chars() walks the text one character at a time, and .count() counts them: 5.
  • .as_bytes() shows the raw bytes. .bytes() walks the same bytes one at a time.
  • .char_indices() gives each character with the byte where it starts. Notice the jump from byte 1 to byte 3. The é uses bytes 1 and 2.

Watching bytes become characters

How does .chars() know that 195 and 169 belong together? Each byte says what it is. The animation walks through “héllo” byte by byte.

bytes chars 0 1 2 3 4 5 104 195 169 108 108 111 104 195 169 108 108 111 h é é is 2 bytes l l o &s[0..2] panics 6 bytes, no chars read yet chars so far: h (1 byte) chars so far: hé (3 bytes) .len() is 6, .chars().count() is 5 a slice must start and end between chars "héllo" in memory: 6 bytes, shown here as numbers 104 is below 128, so it is a whole char on its own: h 195 starts a 2-byte char, so 195 and 169 together are é 108, 108 and 111 are below 128: one char each, l, l, o &s[0..2] would end inside é, so Rust panics

A character is one to four bytes. The first byte of each character says how many bytes it uses, so Rust can always find where one character ends and the next begins.

Here are those steps in words, in case the animation doesn’t play for you:

  1. “héllo” is six bytes in memory: 104, 195, 169, 108, 108, 111. They sit at byte positions 0 to 5.
  2. Byte 104 is below 128, so it’s a plain ASCII character on its own: h.
  3. Byte 195 is a byte that starts a 2-byte character. So 195 and the 169 after it belong together, and the two of them make é.
  4. Bytes 108, 108 and 111 are each below 128, so they’re l, l and o. Six bytes have become five characters.
  5. A slice &s[0..2] would end at byte 2, between 195 and 169. That’s the middle of é, so Rust panics instead of handing you half a character.

You can see the pattern in the bits. Here are the same six bytes in binary:

fn main() {
    for b in "héllo".bytes() {
        println!("{b:3} = {b:08b}");
    }
}

It prints:

104 = 01101000
195 = 11000011
169 = 10101001
108 = 01101100
108 = 01101100
111 = 01101111

A byte that starts with 0 is a whole character. A byte that starts with 110 starts a 2-byte character. A byte that starts with 10 is a “continuation” byte, the second half of something. (Bytes starting 1110 and 11110 start 3-byte and 4-byte characters.) A continuation byte can never be the first byte of a character, and that’s how Rust can check that a slice starts and ends in the right places.

Explain it like I’m ten

Picture a train. Each seat has a number: seat 0, seat 1, seat 2. Most passengers take one seat. A few big passengers take two seats, and some take three or four.

The train keeps a count of seats, not passengers. If you ask “how long is the train?”, you get the number of seats. If you ask “who is in seat 2?”, you might be pointing at the second half of a big passenger. That’s not a whole person. So the conductor won’t answer the question “who’s in seat N?”. You have to walk along the train and count passengers instead.

The precise version

A str is a sequence of bytes that Rust guarantees is valid UTF-8. A char is one Unicode scalar value, which is 4 bytes in memory as a char and 1 to 4 bytes inside a string. .len() returns the byte count, which is stored, so it’s instant. Finding the Nth character means decoding from the start, so it takes time proportional to N. Rust doesn’t let s[n] hide that cost, and it won’t hand you a single byte as if it were a character.

Where the analogy breaks: what a reader sees as one letter can be more than one char. The é can also be written as a plain e followed by a separate “combining accent” character. It looks the same on screen, but it’s 2 chars and 3 bytes:

fn main() {
    let one = "\u{e9}";
    let two = "e\u{301}";
    println!("{one} {} chars, {} bytes", one.chars().count(), one.len());
    println!("{two} {} chars, {} bytes", two.chars().count(), two.len());
    println!("same text? {}", one == two);
}

It prints:

é 1 chars, 2 bytes
é 2 chars, 3 bytes
same text? false

So a passenger isn’t always one person. A letter the reader sees is called a “grapheme cluster”. The standard library doesn’t count those. Real projects use the unicode-segmentation crate for that, which this std-only series doesn’t use.

Why s[0] doesn’t compile

In most languages, s[0] gives you the first character. In Rust:

fn main() {
    let s = String::from("hello");
    let first = s[0];
    println!("{first}");
}

It prints:

error[E0277]: the type `str` cannot be indexed by `{integer}`
 --> src/main.rs:3:19
  |
3 |     let first = s[0];
  |                   ^ string indices are ranges of `usize`
  |
  = help: the trait `SliceIndex<str>` is not implemented for `{integer}`
  = note: you can use `.chars().nth()` or `.bytes().nth()`

Read it from the top:

  • “the type str cannot be indexed by {integer}“. You can’t put a single number inside [] on a string. {integer} means “some integer type the compiler hasn’t pinned down yet”.
  • “string indices are ranges of usize“. What you can put inside [] is a range, like 0..2. That gives you a slice, not a character.
  • The note: names the two honest questions you might mean: “the Nth character” or “the Nth byte”.

Even “hello”, which is all ASCII, doesn’t compile. Rust decides by the type, not the text, and str never takes a single number.

Here are both of those questions, answered:

fn main() {
    let s = String::from("héllo");
    println!("{:?}", s.chars().nth(1));
    println!("{:?}", s.chars().nth(9));
    println!("{}", s.as_bytes()[1]);
}

It prints:

Some('é')
None
195

.chars().nth(1) is the character at position 1. The answer is wrapped in Some, because the string might be too short: asking for character 9 gives None. Part 11 covers Option, the type behind Some and None. For now, read Some('é') as “there is one, and it’s é“.

When you really want bytes, .as_bytes() gives you a byte slice, &[u8], and that one you can index with a number. Byte 1 is 195, which is only the first half of é.

Slicing by byte range

A range does work, and it counts bytes:

fn main() {
    let s = String::from("héllo");
    println!("{}", &s[0..1]);
    println!("{}", &s[0..3]);
    println!("{}", &s[3..]);
}

It prints:

h
hé
llo

&s[0..3] is bytes 0, 1 and 2, which is h plus both bytes of é. &s[3..] runs from byte 3 to the end.

Now cut one byte short:

fn main() {
    let s = String::from("héllo");
    let part = &s[0..2];
    println!("{part}");
}

It prints:

panicked at src/main.rs:3:18:
end byte index 2 is not a char boundary; it is inside 'é' (bytes 1..3) of `héllo`

This compiles, and then it panics when it runs. A panic stops the program with a message. Part 12 covers panics and when to use them. The compiler can’t catch this one, because the numbers in a range can come from anywhere, even from user input.

The message says exactly what went wrong. The end of the range, byte 2, is “inside é“, which uses bytes 1 to 3 (not counting 3). A &str must always be valid UTF-8, so Rust refuses to make one that ends with half a character.

Building strings

A String grows. A &str doesn’t. To build text, start with a String:

fn main() {
    let mut s = String::new();
    s.push('h');
    s.push_str("ello");
    s.push_str(", world");
    println!("{s} ({} bytes)", s.len());

    let name = String::from("Ana");
    let greeting = String::from("hi, ") + &name + "!";
    println!("{greeting}");

    let city = "Lisbon";
    let line = format!("{name} lives in {city} ({} letters)", city.len());
    println!("{line}");
}

It prints:

hello, world (12 bytes)
hi, Ana!
Ana lives in Lisbon (6 letters)
  • push adds one char. A char literal uses single quotes: 'h'.
  • push_str adds a &str.
  • + joins a String on the left with a &str on the right. It takes the left-hand String and gives back a longer one. After let b = a + "x";, you can’t use a any more. Part 6 explains why: the String is moved.
  • format! works like println!, but it gives you the text as a new String instead of printing it. When you join more than two pieces, it’s usually the clearest choice.

+ needs an owned String on its left. Two &str values can’t be added:

fn main() {
    let s = "hello" + " world";
    println!("{s}");
}

It prints:

error[E0369]: cannot add `&str` to `&str`
...
  = note: string concatenation requires an owned `String` on the left
help: create an owned `String` from a string reference

The help: line suggests "hello".to_owned() + " world", which works, and so does format!.

Common methods

These are the ones you’ll reach for most:

fn main() {
    let line = "  Rust is fast, Rust is safe  ";
    let t = line.trim();
    println!("[{t}]");
    println!("{}", t.to_uppercase());
    println!("{}", t.contains("safe"));
    println!("{}", t.replace("Rust", "Ferris"));
    for word in t.split_whitespace() {
        print!("({word})");
    }
    println!();

    let n: i32 = "42".parse().unwrap();
    println!("{}", n + 1);
    println!("{:?}", "4two".parse::<i32>());
}

It prints:

[Rust is fast, Rust is safe]
RUST IS FAST, RUST IS SAFE
true
Ferris is fast, Ferris is safe
(Rust)(is)(fast,)(Rust)(is)(safe)
43
Err(ParseIntError { kind: InvalidDigit })
  • trim removes spaces, tabs and newlines from both ends. It returns a &str view into the original text. Nothing is copied.
  • to_uppercase and to_lowercase return a new String. They handle more than ASCII: "straße".to_uppercase() is "STRASSE", one letter longer.
  • contains asks whether some text appears anywhere in the string.
  • replace returns a new String with every match replaced.
  • split_whitespace gives the words one at a time, each as a &str view. It splits on any run of spaces, so the comma stays with “fast,”.
  • parse turns text into a number, or into other types. You tell it which type you want, either with a type on the variable (let n: i32) or with ::<i32>. It can fail, so it returns a Result. Part 12 covers Result. For now, read .unwrap() as “I’m sure this worked; panic if it didn’t”, and Err(...) as “it didn’t work, and here’s why”.

Worked example: cutting a name to fit

A screen has room for 4 characters of each name. The first try slices by bytes:

fn main() {
    let names = ["Mark", "Fred", "Renée"];
    for name in names {
        let short = &name[..4];
        println!("{short}");
    }
}

It prints:

Mark
Fred
end byte index 4 is not a char boundary; it is inside 'é' (bytes 3..5) of `Renée`

The first two names work, so this bug can hide for a long time. Then “Renée” arrives. Read the panic line: byte 4 is “inside é“, which takes bytes 3 and 4. The slice ..4 asked for bytes 0 to 3, which ends halfway through the é.

&name[..4] means “the first 4 bytes”, but we wanted “the first 4 characters”. Say that instead:

fn first_chars(text: &str, n: usize) -> &str {
    match text.char_indices().nth(n) {
        Some((end, _)) => &text[..end],
        None => text,
    }
}

fn main() {
    let names = ["Mark", "Fred", "Renée", "Al"];
    for name in names {
        println!("{:5} -> {}", name, first_chars(name, 4));
    }
}

It prints:

Mark  -> Mark
Fred  -> Fred
Renée -> René
Al    -> Al

char_indices().nth(n) finds the byte where character number n starts. That’s always a boundary between characters, so slicing up to it is safe. If the text has fewer than n + 1 characters, nth gives None, and we return the whole text. (match with Some and None is Part 11. The idea here is just “if there is one, use it; otherwise keep everything”.)

The returned &str is a view into the name, so nothing is copied.

Worked example: reading a shopping list

Text from a file or a user is messy: extra spaces, mixed case, numbers stored as text. Here’s a list to total up:

fn main() {
    let input = "  Apples 3\nbread 1\n\n  MILK   2  \neggs twelve\n";
    let mut total = 0;
    let mut report = String::new();

    for line in input.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let mut parts = line.split_whitespace();
        let item = parts.next().unwrap_or("").to_lowercase();
        let count_text = parts.next().unwrap_or("");
        let count: u32 = count_text.parse().unwrap_or(0);
        if count == 0 {
            report.push_str(&format!("skipped {item}: '{count_text}' is not a number\n"));
            continue;
        }
        total += count;
        report.push_str(&format!("{item} x{count}\n"));
    }

    print!("{report}");
    println!("total items: {total}");
}

It prints:

apples x3
bread x1
milk x2
skipped eggs: 'twelve' is not a number
total items: 6

Step by step:

  • lines() splits the text at each newline. let line = line.trim(); shadows the old line (Part 2), and the blank line trims to "", which is_empty skips.
  • split_whitespace copes with the extra spaces around “MILK 2”. parts.next() takes the next word, and unwrap_or("") means “or an empty string if there isn’t one”.
  • to_lowercase makes “Apples” and “MILK” match the others.
  • parse().unwrap_or(0) turns “3” into 3, and turns “twelve” into 0 instead of panicking.
  • push_str(&format!(...)) needs the & because push_str takes a &str and format! gives a String.

Using 0 to mean “not a number” works here only because a count of 0 is never valid. Part 12 shows the proper way, which keeps the error.

Tips and traps

  • Using .len() as a letter count. It counts bytes. A name with an accent or an emoji gives a bigger number than you expect. When you mean characters, use .chars().count().
  • Slicing by a number you computed. &s[..n] panics with “is not a char boundary” if byte n lands inside a character. Find a safe end with char_indices, as in the worked example, or check with s.is_char_boundary(n) first.
  • Taking String when you only read. A parameter of type String forces every caller to hand over an owned string. Take &str instead; it accepts literals, slices and &some_string.
  • Adding two literals. "a" + "b" is E0369. Put a String on the left, or use format!.
  • Expecting + to leave the left side alone. let c = a + &b; uses up a. If you still need a, write format!("{a}{b}"). Part 6 explains what “uses up” means.
  • Forgetting that trim and split_whitespace return views. They point into the original string, so they’re cheap. If you need the text to outlive the original, turn it into a String with .to_string().

.len() counts bytes, and a character can be up to four of them.

Exercises

Exercise 1. Without running it, decide what this prints:

let s = "naïve";
println!("{} {}", s.len(), s.chars().count());

Exercise 2. This program panics. Fix it so that it prints crè, the first three characters of the word. Your fix should give the first three characters of any word you put there.

fn main() {
    let word = "crème";
    println!("{}", &word[..3]);
}

It prints:

end byte index 3 is not a char boundary; it is inside 'è' (bytes 2..4) of `crème`

Exercise 3. Write a program that turns "ada lovelace" into the initials A.L.. Use split_whitespace, chars, to_uppercase and push. Don’t slice with byte ranges.

Answers

1. It prints 6 5. The ï takes 2 bytes, so there are 6 bytes and 5 characters:

fn main() {
    let s = "naïve";
    println!("{} {}", s.len(), s.chars().count());
}

It prints:

6 5

2. The è takes bytes 2 and 3, so ..3 ends in the middle of it. The real trouble is that ..3 asks for bytes when you meant characters. Ask for characters:

fn main() {
    let word = "crème";
    let first_three: String = word.chars().take(3).collect();
    println!("{first_three}");
}

It prints:

crè

chars().take(3) gives the first three characters, and collect puts them into a new String. Part 17 covers collect. The first_chars function from the worked example works too, and returns a view instead of a copy.

3. Take the first character of each word, make it uppercase, and push it with a dot:

fn main() {
    let name = "ada lovelace";
    let mut initials = String::new();
    for word in name.split_whitespace() {
        for c in word.chars().take(1) {
            initials.push_str(&c.to_uppercase().to_string());
            initials.push('.');
        }
    }
    println!("{initials}");
}

It prints:

A.L.

word.chars().take(1) gives at most one character, so the inner loop runs once per word, or not at all for an empty word. c.to_uppercase() on a char can give more than one character (ß becomes SS), so we turn it into a String with to_string and push that.

What’s next

String keeps coming up with “Part 6 explains why”. In Part 6, we look at who owns a value, what a move does in memory, and why let b = a; makes a stop working.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.