Rust Basics

Rust Strings: String vs &str

Rust has two string types. Learn when to use each, and how to grow, search and split text.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • String and &str
  • push_str and push
  • contains, split, len
Two string types
&str
  • a borrowed view
  • fixed size
  • "Hello"
String
  • owns its text
  • can grow
  • String::from("Hello")

An owned string and a borrowed view

Rust has two main string types. &str is a view of text stored somewhere else, such as a literal in your code. String owns its text and can grow.

String::from copies the literal into a String that the program owns, so push_str and push can add to it. len counts bytes, not characters. split returns the parts between the separator, one at a time.

Key points

  1. &str borrows text stored somewhere else.
  2. String owns its text and can grow.
  3. len counts bytes, not characters.

Runnable Rust example

Rust
Run code →
main.rs
fn main() {
    let greeting = "Hello"; // &str: a borrowed string slice
    let mut message = String::from(greeting); // String: owned and growable
    message.push_str(", Rust");
    message.push('!');

    println!("{message}");
    println!("length: {}", message.len());
    println!("upper: {}", message.to_uppercase());
    println!("contains Rust: {}", message.contains("Rust"));

    for word in message.split(", ") {
        println!("{word}");
    }
}
Get a Run button for this example Result of running the code
Hello, Rust!
length: 12
upper: HELLO, RUST!
contains Rust: true
Hello
Rust!

Practice

Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.

Finished this lesson?

Mark it as learned to track your progress.

Next: Reverse a String →

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges