typestar

Slices in Rust

Borrowing a contiguous part of a string or array.

fn first_word(s: &str) -> &str {
    match s.find(' ') {
        Some(i) => &s[..i],
        None => s,
    }
}

fn main() {
    let phrase = String::from("touch typing code");
    let word = first_word(&phrase);
    let nums = [1, 2, 3, 4, 5];
    let middle = &nums[1..4];
    println!("{word} {}", middle.len());
}

How it works

  1. &s[..i] slices a string without copying.
  2. Returning a &str borrows from the input.
  3. &nums[1..4] slices an array the same way.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
273
Tokens
106
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 1 of 4 in Slices & strings, step 7 of 15 in Ownership & borrowing.

← Previous Next →

Slices in other languages