Rust Syntax & Basic Constructs
Estimated reading: 3 minutes 29 views

🦀 Rust – Strings: Mastering Text Handling with String and &str

🧲 Introduction – Why Learn Strings in Rust?

Text handling in Rust is powerful but different from many languages. Rust has two main types for representing strings—String and &str—each serving different memory and ownership roles. Understanding these types is key to building applications that work with user input, files, APIs, or text processing.

🎯 In this guide, you’ll learn:

  • The difference between String and &str
  • How to create, modify, and slice strings
  • String concatenation and formatting
  • Best practices for string usage in Rust

🔤 String vs &str: What’s the Difference?

TypeDescriptionOwnershipMutability
&strString slice (borrowed)BorrowedImmutable
StringGrowable, heap-allocated UTF-8 stringOwnedMutable

✍️ Creating Strings in Rust

✅ String Literals (&str)

fn main() {
    let greeting: &str = "Hello, Rust!";
    println!("{}", greeting);
}

✅ Owned String Type

fn main() {
    let name = String::from("Rustacean");
    println!("Hello, {}", name);
}

You can also use .to_string():

let title = "Rust".to_string();

🛠️ Modify a String

Only String (not &str) is mutable and can be modified.

fn main() {
    let mut msg = String::from("Hello");
    msg.push('!');             // Add a single character
    msg.push_str(" Rustacean"); // Add a string slice
    println!("{}", msg);
}

📤 Output:

Hello! Rustacean

➕ Concatenation and Formatting

✅ Using + Operator

fn main() {
    let a = String::from("Rust");
    let b = String::from("Lang");
    let c = a + " " + &b; // a is moved here
    println!("{}", c);
}

⚠️ Note: a is moved, not cloned.

✅ Using format! (Recommended)

fn main() {
    let lang = "Rust";
    let level = "Beginner";
    let msg = format!("Learning {} at {} level", lang, level);
    println!("{}", msg);
}

📌 format! doesn’t take ownership and returns a new String.


🔍 String Length and Slicing

fn main() {
    let s = String::from("Hello");
    println!("Length: {}", s.len());
    println!("Slice: {}", &s[0..2]); // "He"
}

⚠️ Be cautious: Rust strings are UTF-8 encoded. Slicing non-ASCII characters might panic.


🔄 Iterate Over Characters

fn main() {
    let s = String::from("Rust");
    for ch in s.chars() {
        println!("{}", ch);
    }
}

🚫 Common String Mistakes

MistakeError/IssueFix
Mixing String and &strType mismatchUse &str with +, or format!()
Modifying &strNot allowed (it’s immutable)Convert to String with .to_string()
Invalid UTF-8 slicingPanic at runtimeAlways slice at character boundaries

📌 Summary – Recap & Next Steps

Rust’s string handling is robust, safe, and expressive—when you understand the roles of String and &str. With tools like format!, push_str(), and chars(), you can manipulate text efficiently while maintaining memory safety.

🔍 Key Takeaways:

  • String is heap-allocated and mutable; &str is a string slice and immutable
  • Use .to_string() or String::from() to convert
  • Use format!() to concatenate without moving ownership
  • Be mindful of UTF-8 slicing and iteration

⚙️ Up next: Learn about Rust – Booleans and how logical values drive decision-making in Rust programs.


❓FAQs


What’s the main difference between String and &str in Rust?
&str is an immutable string slice (borrowed), while String is an owned, growable string stored on the heap.


How do I convert &str to String?
✅ Use .to_string() or String::from():

let s: String = "hello".to_string();

Can I modify a String after creation?
✅ Yes, if declared mut. Use .push() and .push_str() to modify its contents.


Why can’t I slice strings at arbitrary indexes?
✅ Rust strings are UTF-8 encoded, so slicing must align with valid character boundaries, not byte offsets.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Rust – Strings

Or Copy Link

CONTENTS
Scroll to Top