String

The String type is a heap-allocated, growable UTF-8 string.

Construction

let s = "Hello, world!";           // string literal
let empty = String::new();          // empty string
let from_chars = String::from("hello");

Operations

Length

let len = s.len();       // byte length
let empty = s.is_empty();

Concatenation

let greeting = "Hello, " + name;
let full = first + " " + last;

Comparison

if s == "hello" {
    // string equality
}

Substring and Indexing

let first_byte = s[0];       // byte at index (u8)
let sub = s.substring(0, 5); // substring by byte range

Conversion

let n: i32 = 42;
let s = n.to_string();       // "42"

let x: f64 = 3.14;
let s = x.to_string();       // "3.14"
let found = s.contains("world");
let pos = s.find("world");          // Option<usize>
let starts = s.starts_with("Hello");
let ends = s.ends_with("!");

Transformation

let upper = s.to_uppercase();
let lower = s.to_lowercase();
let trimmed = s.trim();

Split

let parts = s.split(",");    // Vec<String>
let lines = s.split("\n");

Memory Layout

String {
    data: *mut u8,     // pointer to UTF-8 bytes
    len: usize,        // byte length
    capacity: usize,   // allocated capacity
}

Strings are heap-allocated and own their data. When a String is dropped, its memory is freed.