Slices
We'll cover the following...
Let’s add another number to our array. Can you find the bug?
Press + to interact
let numbers: [i32; 5] = [2, 3, 8, 1, 9, 4];
The bug is that our type still says that the array should have 5 values, but it has 6. So, you dutifully oblige the compiler and update the type. All well and good. But let’s go back to that sum
function exercise. Assuming you did the bonus, you probably ended up with a type signature that looks like:
Press + to interact
fn sum(array: &[i32; 5]) -> i32
So, you think to yourself, I’ll just update that to be 6 instead of 5. But what if you want to sum more than one array, and they’re different sizes? Having to define a sum_5
, sum_6
, and so on seems pretty bad.
Fortunately, Rust isn’t that cruel. ...
Access this course and 1400+ top-rated courses and projects.