Check out a free preview of the full The Rust Programming Language course

The "Borrowing Exercise" Lesson is part of the full, The Rust Programming Language course featured in this preview video. Here's what you'd learn in this lesson:

Students are instructed to use references, borrowing, and slices to solve the compiler error, call product(), call average(), and use .clone() or change the function to return a tuple.


Transcript from the "Borrowing Exercise" Lesson

>> Let's move on to the exercise for part six, which is going to look familiar. Because it's exactly the same as the exercise for part five, except now we have some new tools, that we can use to solve it more elegantly than before, as promised. So once again, we have sum of numbers, product of norms, same setup as before, we have this vec of numbers.

Same sum product and average functions. Everything's exactly the same thing as before. Except, now we have two new ways that we can do this. And one is to have, this thing except a reference to a vac of i64, instead of vec of i64. That's straightforward but, as a bonus, I recommend trying to also have it accept a slice.

Using ampersand i64 and the dot as slice method or you can say, use the like square brackets if you want to just give it a sub slice. Whatever you prefer to do there. Basically the reason that I suggest doing this is that in practice you'll actually encounter this quite a lot, in Rust documentation because.

Basically since, slices don't require any heap allocations, it's pretty common practice the C functions, that will say, give me a slice of this thing. And it's understood that most likely what you have is a vec. But because converting between vec and slice is so cheap. This is a little bit more flexible to accept a slice because now, it works with either a slice or a vec.

Whereas if you require, passing in a reference to a vec, that means that, if all you've got is a slice, you can't pass that to the function. So I recommend trying it both ways, that definitely the quicker way is option one. Where you just add, change these two reference types and then borrow.

But option two where you accept a slice, is sort of the more involved way of doing it, but not by a whole lot.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now