Caro is thinking out loud

Created Last updated

A Rust string slice is a reference to part of a String

let s = String::from("hello world");  // a String

let hello: &str = &s[0..5];  // a string slice
let world: &str = &s[6..11];
let s2: &String = &s;  // a normal reference to a whole string

// string literals are also slices
let s_literal = "Hello, world!";  // this guy is a &str

Slices are special kinds of references because they are “fat” pointers, or pointers with metadata, which in this case is the length of the slice.

Sources