Rust•Strings
Rust Strings: String vs &str and UTF-8 Slicing
Learn UTF-8 string representation in Rust, slicing, format!, and passing &str into functions.
Syntax
let s: String = String::from("hello");
let slice: &str = &s;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| String | Owned Type | Growable, mutable heap-allocated string buffer. |
| &str | Borrowed Slice | Immutable reference to a UTF-8 character buffer. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Rust locally:
fn main() {
let mut s = String::from("Compilra");
s.push_str(" Cloud");
println!("Full String: {}", s);
println!("Byte Length: {}", s.len());
// Pass string slice &str
print_badge(&s);
print_badge("Direct Literal");
}
fn print_badge(title: &str) {
println!("-> Badge: [{}]", title);
}Expected Output:
Full String: Compilra Cloud Byte Length: 14 -> Badge: [Compilra Cloud] -> Badge: [Direct Literal]
How It Works: Step-by-Step
- Lines 2-3: Creates growable String and appends &str using push_str.
- Lines 12-14: Function accepts &str, allowing both &String and string literals without copying.
Key Concepts
- Prefer &str as function parameter types so callers can pass both &String and string literals.
- Rust strings are strictly verified valid UTF-8 sequences.
Common Mistake: Attempting to index a string like s[0]
Rust forbids s[0] because UTF-8 characters can be variable byte lengths. Use .chars().nth(0).
❌ Incorrect
let c = s[0]; // Compile Error: `String` cannot be indexed by `{integer}`✅ Correct
let c = s.chars().next(); // Returns Option<char>
Related Rust Tutorials & Compiler
Rust Vectors (Vec<T>): Dynamic Heap Arrays and Slices
Master dynamic Vec<T> collections using vec! macro, push, pop, and indexing.
Rust Console Output: println! and Formatting Macros
Master println!, format!, and debug formatting ({:?}) in Rust.
Rust Default Immutability, the mut Modifier, and Shadowing
Master Rust variable binding model: default immutability, explicit mut modifier, variable shadowing, and compile-time thread safety.
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.