Start learning free

LESSON 64 OF 348 · STRINGS I

String vs &str in Rust in Rust

Lesson

Most languages have one string type. Rust has two, and telling them apart is the single biggest string hurdle for beginners:

  • &str — a borrowed slice: a read-only view into text that lives somewhere else. Every string literal like "Algo" is a &str. You can read it, but you can never grow or shrink it.
  • String — an owned, growable buffer. Your program owns the bytes, so it may append to them, clear them, or hand them to someone else.

Moving between the two is everyday Rust: call .to_string() on a slice to get your own String, and borrow a &str back out of a String whenever you only need to look:

let mut name: String = "Al".to_string(); // owned copy of the literal
name.push_str("go");                     // grow it — only String can do this
let peek: &str = &name[0..2];            // borrow a read-only window: "Al"

&name[0..2] is a range slice: it borrows the bytes from index 0 up to (but not including) 2. And a plain &String automatically coerces to &str, which is why functions usually accept &str.


The trap:

Sooner or later you will hand a literal to something that wants a String. The compiler stops you with this exact error — read the help: line, it hands you the fix:

error[E0308]: mismatched types
 --> src/main.rs:2:25
  |
2 |     let owned: String = "Algo";
  |                ------   ^^^^^^ expected `String`, found `&str`
  |                |
  |                expected due to this
  |
help: try using a conversion method
  |
2 |     let owned: String = "Algo".to_string();
  |                               ++++++++++++

The literal is a borrowed &str; the annotation demands an owned String. They are different types, and the conversion — .to_string() — is always explicit. The reverse mistake is trying to grow a literal: "Algo".push_str("Cademy") fails too, because push_str only exists on String.


Assignment
Follow the Coding Tutorial to make the round trip: borrowed → owned → borrowed again.

  • Bind the literal "Algo" to slice with the explicit type &str.
  • Convert it into a mutable owned String named owned using .to_string().
  • Append "Cademy" with push_str and print owned.
  • Slice the first four bytes back out as first_four: &str using &owned[0..4] and print it.
  • Print the length of owned with .len().

The exact expected output is:

owned = AlgoCademy
first_four = Algo
len = 10

Hint
If the compiler says expected `String`, found `&str`, you forgot .to_string(). If push_str complains, check two things: the target must be a String (not a literal) and its binding must be mut.


STEP 1 OF 7
    Ctrl + Enter to check

    String Vs Str in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free