CodeBlanks Logo Icon CodeBlanks

Summary - Slices

Combine string and array slices to write a first-word function.

Slices summary

A slice is a borrowed view of contiguous data: &str for text, &[T] for arrays and vectors. Ranges take the forms a..b (b excluded), a..=b (included), ..b, a.. and ... String indexes are byte positions; slicing off a char boundary panics, and the safe option is get. Taking slices in function parameters is the most flexible choice.

What to choose when?

If you only read the data, take a slice; if you return a part of the input, return a slice. If you produced new data (joining, uppercasing), return an owned type: String or Vec<T>. Since a slice can't outlive its source, returning a slice of a local variable is a compile error.

Practice Last n elements

Write fn son_n(v: &[i32], n: usize) -> &[i32]; it returns &v[v.len() - n..]. Print the result for [1, 2, 3, 4, 5] and n = 2 with {:?}.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn son_n(v: &[i32], n: usize) -> &[i32] {
    &v[v.len() - n..]
}

fn main() {
    let a = [1, 2, 3, 4, 5];
    println!("{:?}", son_n(&a, 2));
}

Expected output

[4, 5]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 For <code>let v = [1, 2, 3, 4]; let s = &amp;v[1..3];</code>, what is <code>s.len()</code>?

  • 1
  • 2 Correct answer
  • 3
  • 4

Explanation: The range 1..3 covers indexes 1 and 2: [2, 3].

2 Safe slice

Question
let s = "abc";
let x = s.____(1..5);   // None
Answer
let s = "abc";
let x = s.get(1..5);   // None

Explanation: get returns None instead of panicking on an out-of-bounds range.

3 Type and meaning

Term Meaning
&str Text slice
&[T] Element slice
&mut [T] Mutable slice
RangeInclusive a..=b

All lessons in Beginner