← 講座に戻る: Rust from scratch

Slices and week 3 review

動画は近日公開

A slice is a reference to a contiguous part of a collection, without taking its ownership. It is the way to say "look at these elements from 2 to 5" without copying anything. The two slices you will use the most are &str, a portion of text, and &[T], a portion of an array or vector. They are the finishing touch of the ownership week: they combine borrowing with the guarantee that you cannot keep a piece of data that was already modified or freed.

Text slices: &str

They are created with a range over a String: &s[0..5] is the part from byte 0 to 4. Text literals such as "hello" are already of type &str: a slice that points to data stored inside the program itself. That is why, in function signatures, it is better to accept &str than &String: it works with both, because &String converts to &str automatically. An important detail: the indexes are bytes, not letters. If you cut in the middle of a multi-byte character (like ñ), the program panics.

rust
fn first_word(text: &str) -> &str {
    for (i, byte) in text.bytes().enumerate() {
        if byte == b' ' {
            return &text[..i];
        }
    }
    text
}

fn main() {
    let sentence = String::from("hello brave world");
    let hello = &sentence[0..5];
    let world = &sentence[12..];
    println!("{hello} | {world}");

    println!("{}", first_word(&sentence)); // &String -> &str
    println!("{}", first_word("rust lang")); // literal is &str
}

The great advantage of slices over returning a simple index is safety. If first_word returned a number, that number could become stale when the String changes. With a slice, the compiler knows a borrow exists and does not let you modify the String while you use the slice. This removes bugs that in other languages show up only in production. The following code does not compile on purpose, and it is a good demonstration.

rust
// Does NOT compile on purpose: clear() needs &mut while a slice is alive
fn main() {
    let mut s = String::from("hello world");
    let word = &s[0..5];
    s.clear(); // error: cannot borrow `s` as mutable
    println!("{word}");
}

Array and vector slices

The same concept works for any sequence: &[i32] is a slice of integers. A function that accepts &[i32] can receive an array, a vector or a part of any of them, regardless of the length. It is far more flexible than fixing [i32; 4] as we did in week 2. Slices know their length (len), can be walked with for and offer useful methods such as first, last, contains, iter and windows.

rust
fn sum(values: &[i32]) -> i32 {
    let mut total = 0;
    for v in values {
        total += v;
    }
    total
}

fn main() {
    let numbers = [1, 2, 3, 4, 5, 6];
    println!("{}", sum(&numbers));        // whole array
    println!("{}", sum(&numbers[2..5]));  // 3 + 4 + 5
    println!("{:?}", &numbers[..2]);
    println!("{:?} {:?}", numbers.first(), numbers.last());
}

Week 3 review

  • Each value has a single owner; when it goes out of scope it is freed.
  • Assigning or passing a String moves ownership; Copy types (integers, bool, char) are copied; clone() duplicates explicitly.
  • &T lends for reading (many at once); &mut T lends for modifying (just one, with no other references).
  • A reference can never outlive its data.
  • &str and &[T] are slices: views of part of a collection; prefer them as parameters.
rust
fn longest_word(text: &str) -> &str {
    let mut best = "";
    for word in text.split(' ') {
        if word.len() > best.len() {
            best = word;
        }
    }
    best
}

fn max_of(values: &[i32]) -> i32 {
    let mut max = values[0];
    for &v in values {
        if v > max {
            max = v;
        }
    }
    max
}

fn main() {
    println!("{}", longest_word("the quick brown fox jumped"));
    println!("{}", max_of(&[3, 9, -1, 7]));
}

理解度チェック

問題 1 / 6

What type does the literal "hello" have?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →