Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 132 · Variables and Types

String and &str Basics

Learn the two Rust string types, String and &str - literals, creating and growing strings, + and format!, UTF-8 and len() in bytes, and why a string cannot be indexed by integer.

Text is where many newcomers first stumble in Rust. Other languages have one string type; Rust has two main ones, String and &str, and the rules about which one to use come straight from ownership. Once you see the difference, a lot of Rust's design clicks into place.

In short: a String owns its text, which lives on the heap and can grow. A &str (pronounced "string slice") borrows text that is owned by somebody else, such as a string literal baked into your program or part of a String. This lesson teaches both, shows how to convert between them, explains why len() counts bytes, and explains why s[0] is not allowed. The string handling lesson later goes much deeper into searching, splitting and Unicode.

String literals are &str

Text in double quotes is a string literal. Its type is &'static str: a reference to text stored inside your compiled program, valid for the whole run.

Rust String literals

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

  • A literal may span several lines; the line breaks are part of the text.
  • Escapes such as \n, \t, \" and \\ work as in C. A backslash at the very end of a line removes the line break and the leading spaces of the next line, which is handy for long messages.
  • A raw string r"..." has no escapes at all. When the text itself contains quotes, add hashes: r#"..."#.

Because a literal is a &str, you can never change it. It is read-only text in the program. To build or modify text you need a String.

Creating a String

A String is an owned, growable, UTF-8 text buffer. It is basically a Vec<u8> that the type system guarantees to hold valid UTF-8. You create one from a &str in several equivalent ways:

Rust Creating Strings

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

String::from, .to_string(), .to_owned() and .into() do the same job for a literal: allocate heap memory and copy the text in. Pick String::from("...") or .to_string() and use it consistently. format! works like println! but returns a String instead of printing. String::with_capacity(n) reserves space up front, which avoids repeated reallocation when you know roughly how big the result will be.

Growing a String

The methods push (one char) and push_str (a &str) append in place. The variable must be mut:

Rust push and push_str

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Other useful in-place operations are insert, insert_str, pop, remove(index), truncate(new_len) and clear. Each is a cheap operation on the underlying buffer; if the buffer is full, String allocates a bigger one and moves the text, which happens automatically.

Joining strings: + and format!

You can add a &str to a String with +, but the rules surprise people:

Rust The + operator takes ownership

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The + operator calls a method whose signature is roughly fn add(self, other: &str) -> String. Two things follow:

  • The left side is consumed (moved). Rust reuses its buffer for the result, which is efficient, but first can no longer be used.
  • The right side must be a &str. Passing &second (a &String) works because the compiler converts &String to &str automatically (deref coercion). You cannot add two Strings directly, and you cannot add two literals ("a" + "b" is an error).

With several pieces, the chain of + becomes hard to read. Use format!, which borrows everything and moves nothing:

Rust format! is clearer for several parts

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Choose format! when you assemble text from different values. Choose push_str in a loop when you append to one buffer. Use + only for simple cases such as a + &b.

&str as a borrowed view

A &str can point to a whole literal, a whole String, or any part of either. It consists of a pointer and a length, with no ownership:

Rust Borrowing text with &str

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This is the rule you will apply every day: a function that only reads text should take &str. Callers can then pass a literal, a &String, or a slice of either without any conversion or copy. Taking String forces the caller to give up ownership or clone; taking &String is more restrictive than &str and has no advantage. Slices explains the syntax &owned[6..11] fully.

Type Owns the text? Can grow? Typical use
String yes yes building, storing and returning text
&str no (borrowed) no parameters, literals, views into other text

When a function needs to keep the text (store it in a struct, return it), take or build a String. When it only looks, take &str.

UTF-8: len() counts bytes

Rust strings are always valid UTF-8. In UTF-8, the English letters take one byte, but many characters take two, three or four bytes. The len() method therefore returns the length in bytes, not in characters:

Rust Bytes versus characters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

chars() iterates over Unicode scalar values (Rust's char type, covered in scalar types). bytes() gives the raw bytes. The é takes two bytes (195 and 169), each Japanese character takes three, and the crab emoji takes four.

Note that even chars().count() is not always the number of "letters" a human sees. An accented letter can be written as a base letter plus a combining mark, which is two chars. Full grapheme handling needs an external crate; the standard library works at the level of bytes and scalar values.

Why you cannot index a String

In many languages s[0] returns the first character. In Rust, it is a compile error:

Rust Indexing a string (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler says error[E0277]: the type `str` cannot be indexed by `{integer}` . There are two good reasons for this:

  1. What would s[i] mean? The i-th byte? The i-th char? Because characters have different widths, s[1] in "héllo" would land in the middle of the two-byte é. Returning a byte would give meaningless data; returning a char would require scanning from the start.
  2. Performance promise. Rust indexing is expected to be O(1). Finding the i-th character in UTF-8 is O(n). Rust refuses to hide that cost.

Instead you say what you mean:

Rust Doing it explicitly

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You can slice a string by byte range, &s[0..1], but both ends must fall on a character boundary. If one does not, the program panics. get(range) returns None instead, which is the safe option for text you do not control. The panic is demonstrated in the slices lesson.

&text[a..b] takes byte positions. It works for plain English text, which hides the bug until a user types "é" or "日". When in doubt, use chars(), char_indices() or get.

Comparing and converting

Comparison with == works between any mix of String and &str, and it compares the text. Ordering with < is by bytes (which is Unicode code point order, not alphabetical order in any human language).

Rust Comparing strings and converting to other types

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

parse::<T>() turns text into numbers (and other types), returning a Result that you must handle; reading input shows the proper way. to_string() works on anything that implements Display.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What is the type of the literal "hello"?

    A string literal is a reference to text stored in the program binary, so its type is &'static str. Call to_string() or String::from to get an owned String.
  2. 2. What does "héllo".len() return?

    len() returns the length in UTF-8 bytes. The letter é takes two bytes, so the string has six bytes but five chars.
  3. 3. Given let a = String::from("x"); let b = String::from("y");, which expression compiles?

    The + operator needs an owned String on the left and a &str on the right. &b is a &String that is converted to &str automatically. a is moved into the result.
  4. 4. Why does Rust refuse s[0] for a String?

    UTF-8 characters take 1 to 4 bytes, so a byte index is not a character index. Rust makes you choose chars(), bytes() or a byte-range slice explicitly.
  5. 5. Which parameter type is best for a function that only reads text?

    &str accepts string literals, &String and slices without copying, and does not take ownership of the caller's data.

Summary

  • &str is a borrowed view of UTF-8 text (literals are &'static str); String is an owned, growable, heap-allocated UTF-8 buffer.
  • Create a String with String::from, .to_string() or format!; grow it with push and push_str.
  • a + &b moves a and borrows b; for several parts use format!.
  • Functions that only read text should take &str.
  • len() counts bytes; use chars().count() for scalar values. Byte-range slices must fall on character boundaries.
  • You cannot index a string by integer; use chars(), bytes(), char_indices() or get(range).

Next: Type Aliases, the Never Type and Inference