Loading
0x40Lesson 5 of 17

Work with String and string slices

Understand `String`, `&str`, ownership, and borrowing in text processing.

18 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Use borrowed string slices and owned Strings correctly.

String is an owned, growable UTF-8 buffer. &str is a borrowed view into string data. Most read-only APIs should accept &str so callers can pass either literals or owned strings.

main.rs
1fn shout_prefix(name: &str) -> String {
2    format!("Hi, {}!", name)
3}
4
5fn main() {
6    let user = String::from("Ferris");
7    println!("{}", shout_prefix(&user));
8}
Output
Hi, Ferris!

Prefer &str in parameters when you only need to read text. That keeps APIs flexible and avoids unnecessary moves or clones.

Try it

Up to 15 XP

Owned or borrowed?

Classify each snippet by whether it produces owned text (String) or borrowed text (&str).

0 of 4 sortedScore 0/0
  • “String::from("rust")”

  • “"rust"”

  • “name.trim()”

  • “format!("{}!", word)”

Key takeaways

  • Use borrowed string slices and owned Strings correctly.

  • Rust uses types and ownership rules to prevent common bugs.

  • Small experiments build intuition quickly.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Rust

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning Rust.

Exercise 1

Normalize and greet

+25 XP

Read one line, trim leading/trailing spaces, and print Hello, <name>!.

  • Trims spaces
  • Simple name
main.rs
Loading editor…

Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…