Rust Strings

Rust Tutorial

🦀 Rust Strings

In Rust, strings are more powerful and safer than in many other languages — but also a bit tricky at first.

Rust mainly has two string types:

  1. &str (String Slice)

  2. String (Growable, Heap-allocated String)

Understanding these is VERY IMPORTANT, especially for ownership & memory safety.


🔹 1. &str – String Slice (Immutable)


Characteristics

  • Immutable (cannot change)

  • Stored in read-only memory

  • Very fast

  • Fixed size

✔ Mostly used for string literals


🔹 2. String – Heap Allocated (Mutable)


Characteristics

  • Mutable

  • Stored on the heap

  • Growable

  • Owns its data

✔ Used when string content needs to change


🔹 3. Creating a String

Both are valid.


🔹 4. String Concatenation

▶️ Using push_str()



▶️ Using + Operator


 

⚠️ s1 is moved (ownership transferred)


▶️ Using format! (Best Practice ✅)


 

✔ No ownership issues
✔ Clean & safe


🔹 5. String Length


⚠️ Length is in bytes, not characters.


🔹 6. Indexing Strings ❌ (Not Allowed)

let s = String::from("Rust");
// let c = s[0]; ❌ Error

❌ Because Rust strings are UTF-8 encoded


🔹 7. Iterating Over Characters

 

✔ Safe Unicode handling


🔹 8. Iterating Over Bytes


 


🔹 9. String Slicing


 

⚠️ Slicing must be on valid UTF-8 boundaries


🔹 10. Common String Methods


 

Useful methods:

  • len()

  • is_empty()

  • contains()

  • replace()

  • to_uppercase()

  • split()

  • trim()


🔹 11. Passing Strings to Functions

▶️ Using &str (Recommended)


 

✔ Flexible & efficient


🔑 String vs &str (Important)

Feature String &str
Mutable
Heap allocated
Ownership
Growable
Common use Dynamic text Literals & references

🧠 Key Takeaways

  • Rust strings are UTF-8

  • No direct indexing allowed

  • Prefer &str for function parameters

  • Use String when mutation is needed

  • format! is safest for concatenation

You may also like...