π§΅ Rust String Types: The Tale of Two Strings
Imagine you have two kinds of containers for your toys: a toy box you own (you can add, remove, and rearrange toys) and a display shelf at a museum (you can only look, not touch). In Rust,
Stringis your toy box, andstris the museum shelf!
π― What Weβll Learn
- String type β Your personal, growable toy box
- str type β The museum shelf (read-only view)
- String literals β Pre-made labels in your code
- Raw string literals β Labels with special characters
- String creation β Building your toy box
- String vs str conversion β Moving between box and shelf
π¦ The String Type: Your Personal Toy Box
Think of String as a magic toy box that can grow bigger or smaller whenever you want!
What Makes String Special?
- β Owned β It belongs to YOU
- β Growable β Can get bigger anytime
- β Heap-allocated β Lives in a big storage room
- β Mutable β You can change whatβs inside
// Creating your toy box
let mut my_box = String::from("Hello");
// Adding more toys!
my_box.push_str(", World!");
println!("{}", my_box);
// Output: Hello, World!
Why Use String?
When you need to:
- Build text piece by piece
- Change text after creating it
- Own the data (keep it around)
πΌοΈ The str Type: The Museum Shelf
Now imagine str as a glass display β you can see everything, but you canβt touch or change it!
What Makes str Special?
- π Borrowed β Youβre just looking
- π Fixed size β Canβt grow or shrink
- π Immutable β Read-only view
- π Always used as &str β A reference (like pointing)
// This is a reference to a str
let shelf: &str = "Look but don't touch!";
// We can read it
println!("{}", shelf);
// But we can NOT change it!
// shelf.push('!'); // β ERROR!
The & is Important!
You almost never see str alone β itβs always &str (a reference):
graph TD A["&str"] --> B["Points to text data"] B --> C["Can be in stack"] B --> D["Can be in heap"] B --> E["Can be in binary"]
π·οΈ String Literals: Pre-Made Labels
When you write text directly in your code with quotes, thatβs a string literal!
Simple Example
// This text lives in your program forever
let greeting = "Hello, Friend!";
// Type: &str (a reference to str)
Where Do They Live?
String literals are baked into your program β like labels printed on a box before you even open it!
graph TD A["Your Code"] --> B["greeting = 'Hello'"] B --> C["Compiled Program"] C --> D["Literal stored in binary"] D --> E["&str points here"]
Real-Life Analogy
- String literal = A sticker that comes with your game
- String = A blank sticker you write yourself
// Literal (pre-made sticker)
let pre_made: &str = "I came with the box!";
// String (your own sticker)
let my_own: String = String::from("I made this!");
π¦ Raw String Literals: The Escape Artist
Sometimes you need special characters like \ or " in your text. Raw strings make this easy!
The Problem
// This is confusing with backslashes
let path = "C:\\Users\\Name\\file.txt";
The Solution: Raw Strings!
Use r#"..."# to write text exactly as you see it:
// Much cleaner!
let path = r#"C:\Users\Name\file.txt"#;
// Even quotes work!
let quote = r#"She said "Hello!""#;
Adding More # for More Power
If your text contains "#, add more # symbols:
// Text with "# inside
let tricky = r##"Look: "# is here!"##;
println!("{}", tricky);
// Output: Look: "# is here!
When to Use Raw Strings
| Situation | Use Raw String? |
|---|---|
| File paths on Windows | β Yes! |
| Regular expressions | β Yes! |
| JSON inside code | β Yes! |
| Simple text | β Not needed |
π οΈ String Creation: Building Your Box
There are many ways to create a String!
Method 1: String::new()
Creates an empty toy box:
let mut empty = String::new();
empty.push_str("Now I have toys!");
Method 2: String::from()
Creates a box with toys already inside:
let filled = String::from("Toys inside!");
Method 3: .to_string()
Converts anything text-like into a String:
let from_literal = "Hello".to_string();
let from_number = 42.to_string();
Method 4: format!()
Like making a collage from many pieces:
let name = "Rust";
let year = 2015;
let message = format!(
"{} was created in {}!",
name,
year
);
// Output: Rust was created in 2015!
Quick Comparison
| Method | Use When |
|---|---|
String::new() |
Starting empty, will add later |
String::from("...") |
Have text ready |
"...".to_string() |
Converting from &str |
format!(...) |
Combining multiple values |
π String vs str Conversion
Now the magic: how to move between your toy box and the museum shelf!
From &str to String (Shelf β Box)
When you want to OWN the text:
let shelf: &str = "Just looking";
// Method 1: to_string()
let box1: String = shelf.to_string();
// Method 2: String::from()
let box2: String = String::from(shelf);
// Method 3: to_owned()
let box3: String = shelf.to_owned();
All three work the same! Pick your favorite.
From String to &str (Box β Shelf)
When you want to SHARE a view:
let my_box: String = String::from("My toys");
// Method 1: Reference with &
let view1: &str = &my_box;
// Method 2: as_str()
let view2: &str = my_box.as_str();
Visual Flow
graph LR A["&str"] -->|".to_string#40;#41;"| B["String"] A -->|"String::from#40;#41;"| B A -->|".to_owned#40;#41;"| B B -->|"&"| A B -->|".as_str#40;#41;"| A
Why Does This Matter?
Functions often want &str (because itβs flexible):
fn greet(name: &str) {
println!("Hello, {}!", name);
}
// Works with &str
greet("World");
// Works with String too!
let my_name = String::from("Rustacean");
greet(&my_name); // Just add &
π― Quick Decision Guide
| I want to⦠| Use |
|---|---|
| Change text later | String |
| Just read text | &str |
| Own the data | String |
| Borrow the data | &str |
| Pass to a function | Usually &str |
| Store in a struct | Usually String |
π Key Takeaways
- String = Owned, growable toy box (heap)
- &str = Borrowed, read-only view
- String literals = Text baked into your program
- Raw literals = Use
r#"..."#for special characters - Creation =
String::new(),String::from(),.to_string(),format!() - Conversion = Use
&or.as_str()to go String β &str
π You Did It!
Now you understand the two string types in Rust! Remember:
Stringis your toy box β own it, grow it, change it.&stris the museum shelf β look, but let someone else handle it.
Happy coding, Rustacean! π¦
