Rust Strings
🦀 Rust Strings
Rust mainly has two string types:
-
&str(String Slice) -
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)
❌ Because Rust strings are UTF-8 encoded
🔹 7. Iterating Over Characters
🔹 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
&strfor function parameters -
Use
Stringwhen mutation is needed -
format!is safest for concatenation
