String Types

Back

Loading concept...

🧡 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, String is your toy box, and str is 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

  1. String = Owned, growable toy box (heap)
  2. &str = Borrowed, read-only view
  3. String literals = Text baked into your program
  4. Raw literals = Use r#"..."# for special characters
  5. Creation = String::new(), String::from(), .to_string(), format!()
  6. Conversion = Use & or .as_str() to go String β†’ &str

πŸŽ‰ You Did It!

Now you understand the two string types in Rust! Remember:

String is your toy box – own it, grow it, change it. &str is the museum shelf – look, but let someone else handle it.

Happy coding, Rustacean! πŸ¦€

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.