Skip to content

Rust Strings — Understanding String, &str, and UTF-8 Text Handling

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Rust Strings. We cover key concepts, practical examples, and best practices to help you master this topic.

Rust strings are UTF-8 encoded with String for owned heap data and &str for borrowed slices, supporting indexing via chars() and bytes().

What You'll Learn

  • String vs &str
  • UTF-8 encoding
  • String concatenation
  • String slicing

Why It Matters

Strings are everywhere. DodaZIP uses strings for file paths and metadata. Rust's UTF-8 handling ensures correct international character processing.

Real-World Use

Text processing, file I/O, web API responses, configuration Parsing.

fn main() {
    // String vs &str
    let s1 = String::from("hello");        // Owned
    let s2: &str = "world";                // Borrowed
    let s3 = &s1[..];                      // String -> &str

    // String concatenation
    let s = String::from("Hello, ");
    let s = s + "World!";
    println!("{}", s);

    let hello = "Hello".to_string();
    let world = "World".to_string();
    let s = format!("{} {}", hello, world);
    println!("{}", s);

    // UTF-8 bytes
    let hello = String::from("Hello");
    for b in hello.bytes() {
        print!("{} ", b);
    }
    println!();

    // UTF-8 chars
    let hi = String::from("Hello");
    for c in hi.chars() {
        print!("{} ", c);
    }
    println!();

    // String slicing (careful!)
    let s = String::from("Hello, World!");
    let slice = &s[0..5];
    println!("Slice: {}", slice);
}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro