Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ OWNERSHIP WITHOUT THE PANIC
BUILD NOTE 13 / 53

Borrow exactly the part you need.

Use borrowed ranges without confusing bytes and characters.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

A slice &[T] describes a contiguous range using a pointer and a length. It borrows the elements rather than copying them. A string slice &str additionally guarantees valid UTF-8. String range indexes refer to bytes and must fall on UTF-8 character boundaries. get on a string range returns None for invalid bounds or a split inside a code point, while direct indexing by such a range panics. Work with chars for scalar iteration and a Unicode-aware crate when your product needs grapheme segmentation.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/slices/src/main.rs
fn main() {
    let values = [10, 20, 30, 40];
    let middle = &values[1..3];
    let text = "café";
    println!("{middle:?}");
    println!("prefix={:?}, broken={:?}", text.get(..3), text.get(..4));
}
↳ EXPECTED OUTPUT
[20, 30]
prefix=Some("caf"), broken=None
  1. 1

    The array slice covers indexes 1 and 2.

  2. 2

    The accented é occupies two UTF-8 bytes.

  3. 3

    The ..4 boundary splits that character, so get returns None.

From the extracted rust-workbench folder
cargo run -p lesson_slices

03 Mind the boundary

04 Your next build

A SMALL MISSION

Write first_two accepting &[i32] and returning up to two elements without panicking on an empty input.

Reveal one possible solution +
solutions/slices/src/main.rs
fn first_two(values: &[i32]) -> &[i32] {
    &values[..values.len().min(2)]
}
fn main() {
    assert_eq!(first_two(&[1, 2, 3]), [1, 2]);
    assert_eq!(first_two(&[]), []);
}

05 Check your reasoning

QUICK SIGNAL CHECK

What do Rust string slice indexes count?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.