AnyCompiler

Strings and Slices

A string slice, &str, is a reference to part of a String (or a whole one) — it borrows the underlying text rather than owning it. Slicing with [start..end] gives you a view into the original string without copying its data.

fn main() {
    let s = String::from("hello world");

    let hello = &s[0..5];
    let world = &s[6..11];

    println!("{} {}", hello, world);
}
Output
hello world

String vs &str

String is an owned, growable type — you'll see it whenever a function needs to build or hold onto text. &str is a borrowed view into text that's owned somewhere else, including string literals, which are &str by default. Functions that only need to read a string usually take &str, since it accepts both a String (via a borrow) and a literal.

fn main() {
    let s1: &str = "a string slice";
    let s2: String = String::from("an owned String");

    println!("{}", s1);
    println!("{}", s2);
}
Output
a string slice
an owned String

Next: structs — grouping related data together, and attaching methods to it.

Practice exercise

Given let s = String::from("rust lang"), create a slice first that holds just "rust" (the first 4 characters), then print first.