1. 17
    Rustlings primitive_types4: Referencing contiguous slices of data we don't own using range
    49s

Rustlings primitive_types4: Referencing contiguous slices of data we don't own using range

Chris Biscardi
InstructorChris Biscardi

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

README for this exercise.

Chris Biscardi: [0:00] In primitive_types 4, you're supposed to get a slice out of an array where the questions marks are the test passes. Now that we have a five element array -- 1, 2, 3, 4, 5 -- we're using the assert_eq! Macro to test that 2, 3, 4 is equal to our nice_slice. That means we need to get elements 2, 3, 4, which are 1, 2, 3 index.

[0:20] To do this, we can use a special syntax, we can use the range here like it's a property on a. The range will start at the starting index and end at the ending index. We're starting at index 1 which is 2, and we're ending at 4 which will not include the 4th index.

[0:34] Note that we get an error here, "The size of this slice can't be known at compilation time, consider borrowing here." After including the borrow symbol, the & means we're using a reference to a. In effect, you're borrowing a section of the array as a slice by using a range.