Rust:Rust Strings: String vs &str and UTF-8 Slicing
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:

ParameterTypeDescription
StringOwned TypeGrowable, mutable heap-allocated string buffer.
&strBorrowed SliceImmutable reference to a UTF-8 character buffer.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler