skip to content

In Rust, why does `let first = name[0];` fail to compile when `name` is a `String`, and how do you get its first character?

level: juniorimportance: must knowfreq 75%

answer

  1. UTF-8 bytes, variable width
  2. str indexes by byte ranges only
  3. E0277 and SliceIndex<str>
  4. chars().next() versus as_bytes()[0]

basics

~20 s

A String holds UTF-8 bytes and a character takes one to four of them, so str can be indexed only by byte ranges. name[0] fails with E0277; name.chars().next() gives the first char, name.as_bytes()[0] the first byte.

solid answer

~40 s

A `String` is a growable buffer of UTF-8 bytes, and `name[0]` goes through `Index` on `str`, which is implemented only for ranges of `usize`. rustc rejects it with E0277, "the type `str` cannot be indexed by `{integer}`", and even suggests `.chars().nth()` or `.bytes().nth()`. The design is deliberate: in UTF-8 a character takes one to four bytes, so position 0 could mean a byte, a `char` or a user-visible letter, and an O(1) `[]` could hand back half a character. For the first character write `name.chars().next()`, an `Option<char>` that is `None` for an empty string; for raw bytes write `name.as_bytes()[0]` or `name.bytes().next()`. Note that `name.len()` counts bytes too, so `"Zoë".len()` is 4.

code

rust · 5 lines
rust
fn main() {
    let name = String::from("Zoë");
    let first = name[0];
    println!("{first}");
}

go deeper

for a junior

Recall that String is UTF-8 bytes, that s[0] is a compile error, and that chars().next() gives the first character while len() counts bytes.

for a middle

Explain the mechanism: Index on str is implemented only for SliceIndex<str> ranges, and the Book's three reasons are ambiguity, no honest O(1) and no half characters.

for a senior

Show the habits that follow in real code: keep byte offsets from find or char_indices, prefer Option-returning accessors on untrusted input, and never treat len() as a character count.

for a principal

Frame it as a design trade: Rust moved the cost of variable-width text into the type system, so reviewers should push back on code that collects to Vec<char> just to restore indexing.

## What a `String` actually holds A Rust **`String`** is an owned, growable buffer of bytes that is always valid **UTF-8**; **`str`** is the same bytes without ownership, usually seen as `&str`. UTF-8 is a variable-width encoding: ASCII letters take one byte, `ë` takes two, most CJK characters three, and most emoji four. A Rust **`char`** is something else again: a fixed four-byte Unicode scalar value. So `String` is not a `Vec<char>`, and that single fact explains this whole question. - `"Zoë".len()` is **4**, because `len` counts bytes. - `"Zoë".chars().count()` is **3**, because `chars` decodes scalar values. - `"Zoë".as_bytes()` is `[90, 111, 195, 171]`: the `ë` is the two bytes 195 and 171. ## What rustc says `name[0]` desugars to `*name.index(0)`. `String` and `str` both implement `Index<I>` only where `I: SliceIndex<str>`, a bound that covers the range types (`0..2`, `..3`, `2..`, `..`) but not `usize`. rustc 1.99 reports: ```plaintext error[E0277]: the type `str` cannot be indexed by `{integer}` | let first = name[0]; | ^ string indices are ranges of `usize` = note: you can use `.chars().nth()` or `.bytes().nth()` ``` The same applies to `name.get(0)`: `str::get` takes the same `SliceIndex<str>` bound, so it is E0277 too. ## Why Rust refuses an integer index The Rust Book gives the reasons, and each is worth saying in an interview: 1. **Ambiguity.** "Index 0" could mean the first byte, the first `char` or the first grapheme cluster (what a reader calls a letter, which may be several `char`s). Rust will not pick one silently. 2. **No honest O(1).** Indexing syntax promises constant time. Finding the n-th `char` means decoding every byte before it, which is O(n). 3. **No half characters.** If `[]` returned a byte, `"ë"[0]` would yield 195, a value that is not a character at all, and code that treated it as one would corrupt text. The restriction is in the types, not in the data: `"abc"[0]` is rejected as well, even though every byte there is ASCII. ## What to write instead | You want | Write | Type | Cost | |---|---|---|---| | first character | `name.chars().next()` | `Option<char>` | O(1) | | n-th character | `name.chars().nth(n)` | `Option<char>` | O(n) | | first byte | `name.as_bytes()[0]` | `u8` (panics if empty) | O(1) | | first byte, checked | `name.bytes().next()` | `Option<u8>` | O(1) | | a substring by byte range | `&name[0..2]` | `&str` | O(1), panics off a boundary | | the same, without panicking | `name.get(0..2)` | `Option<&str>` | O(1) | Prefer the `Option`-returning forms on input you did not produce: an empty `String` has no first character, and `chars().next()` says so with `None` instead of panicking. ## Byte ranges compile, with a catch Range indexing is allowed because a byte range is unambiguous and O(1). The catch is that both bounds must fall on **char boundaries**: `&"Zoë"[0..3]` panics at run time because byte 3 sits inside `ë`. Checking boundaries before slicing, and truncating text to a byte budget safely, are separate skills with their own methods (`is_char_boundary`, `floor_char_boundary`). ## Habits that follow - Store positions as **byte offsets** (from `find` or `char_indices`), not as character counts, so later slicing is O(1). - If an algorithm truly needs random access by character, collect once into a `Vec<char>` and index that. - Treat `len()` as a storage size in bytes, never as a character count. ## Fixes that look right and are not Three workarounds appear in code review often enough to name: - **`name.as_bytes()[0] as char`** compiles and works for ASCII, but for a name starting with `É` it turns the lead byte 195 into `'Ã'`, a different letter. A byte cast to `char` is a Latin-1 reading, not UTF-8 decoding. - **`name.chars().collect::<Vec<char>>()[0]`** is correct but allocates a whole vector to read one value, and still panics on an empty string. - **`&name[0..1]`** returns the first character only when it is one byte long; for `Émile` it panics because byte 1 is inside `É`. `name.chars().next()` avoids all three: it decodes exactly one character, allocates nothing and reports an empty string as `None`.

  • Is `name.chars().nth(5)` a cheap substitute for `name[5]`?
    No. `chars()` decodes from the start every time, so `nth(5)` is O(n) and a loop calling it for each position is O(n squared). If you need repeated access by character, collect once into a `Vec<char>`, or keep the byte offsets that `char_indices()` yields and slice with them.
  • Does `&name[0..1]` compile on a `String`?
    Yes. `str` implements `Index` for byte ranges, so it compiles and returns a `&str`. It panics at run time if either bound falls inside a multi-byte character; `name.get(0..1)` performs the same slice but returns `None` instead of panicking.
  • Why is `name.as_bytes()[0]` allowed when `name[0]` is not?
    `as_bytes()` returns a `&[u8]`, and slices of bytes do implement `Index<usize>`. The result is an honest `u8`, not a character, so there is no ambiguity left. It still panics on an empty string, where `name.bytes().next()` returns `None`.

  • name[0] compiles and returns the first byte, as on a byte array.
  • Rust strings are UTF-16, so an integer index would be ambiguous.
  • String::len returns the number of characters.
  • chars().nth(i) is a constant-time lookup.
  • Integer indexing is rejected only when the string contains non-ASCII text.