Work with String and string slices
Understand `String`, `&str`, ownership, and borrowing in text processing.
- 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.
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}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 XPOwned or borrowed?
Classify each snippet by whether it produces owned text (String) or borrowed text (&str).
“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.
Normalize and greet
Read one line, trim leading/trailing spaces, and print Hello, <name>!.
- Trims spaces
- Simple name
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…