How wrong is my summary of borrowing?


#1

I’m writing a blog post for new Rustacians (like myself) that talks about borrowing. I’m trying to describe why a function like

fn work_with_array(a: &[&str]) {
//does stuff
}

fn main() {
  let things = ["one", "two"];
  work_with_array(&things);
}

Needs to borrow the Array and not own it. My current description goes like this:


When our little array is owned by a function, its data is copied when it’s used by work_with_array. There are cases when it’s not copied, but those aren’t relevant here, I think.

When our array is borrowed by our function its data is not copied. Instead the function gets a reference to the location where the data is stored.

When Rust is going to copy data, it has to set aside memory for these things at compilation. For this to work, the types have to match exactly. But if a function only borrows some data, then we don’t have to be a strict, as the data does not have to be copied and extra space does not need to be accounted for.


My description feels truth-y, like I’m close to being correct without not, you know, actually being correct. Thoughts?


#2

When Rust is going to copy data, it has to set aside memory for these things at compilation. For this to work, the types have to match exactly.

I’d say instead that in order for this to work, the compiler has to know (at compile-time) how much memory to set aside and copy. So you can actually pass this array by value if you tell the compiler exactly how long the array is:

fn work_with_array(a: [&str; 2]) {
    //does stuff
}

fn main() {
  let things = ["one", "two"];
  work_with_array(things);
}

But if you want function to accept with arrays of any length, rather than just arrays of length 2, then you need to pass by reference instead.


#3

Thanks! I do get into the [&str; 2] option a bit earlier in the post, but didn’t really illustrate the link between that and memory. Much appreciated!