Skip to main content

String and &str

`String` owns heap memory and can grow. `&str` is a borrowed view into text someone else owns — a string literal, or a slice of a `String`. Nearly every function should take `&str` and return `String` only when it truly produces new text.

Rust strings are UTF-8, always. That is why you cannot index one with a number: byte 3 of a multi-byte character is not a character. Iterate with `.chars()` for characters or `.bytes()` for raw bytes, and be explicit about which one you mean.

`format!` builds a new `String` the same way `println!` builds a line of output, so the same placeholder rules apply.

Indexing a String

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

error[E0277]: the type `String` cannot be indexed by `{integer}`

Use `s.chars().next()` for the first character, or slice a byte range you know is valid: `&s[0..1]`.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust