yewler [she/her]

  • 0 Posts
  • 286 Comments
Joined 7 months ago
cake
Cake day: August 23rd, 2024

help-circle






  • Basically in Rust every piece of data has exactly one owner, and when that owner doesn’t exist anymore, the data doesn’t either. But often times you want to have multiple different ways to access the same data. For example, if you’re calling a function and passing in owned data, there can only be one owner, so the function has to take ownership of that data. When the function returns, the variable that owns that data goes out of scope, and boom there goes that data. So if you try to access that data again after calling the function, you’ll get an error. This is incredibly annoying behavior. What you want is some way for the function to be able to tell the compiler “no no I don’t actually want to own this data, I just want to borrow it.” This is what borrowing is. We’re telling the compiler that we don’t want to tie the lifetime of our data to the variable in the function call. The data will still be lost when the original variable dies, and doesn’t care about the new one. Problem solved. But now that we have a concept of borrowing, it introduces some nuanced potential issues. This is what the borrow checker is for. It’s job is to make sure you haven’t done anything stupid with the power borrows give you.

    For example, its entirely possible for you to write some code that borrows some data, but the owner of that data goes out of scope (taking the data with it) before the borrow does. Then the borrow would be trying to hold onto data that no longer exists. The borrow checker makes sure you don’t do this.

    The second issue you could run into involves mutable references, which I’m sure you’ve seen. Let’s say you have some data owned by some variable. Let’s say that you also have one immutable borrow and one mutable borrow to that data, active at the same time. So the mutable borrow is allowed to make changes to the data, but the immutable borrow is making the assumption that the data can’t change. So the borrow checker won’t let you do this because the whole point of an immutable reference is that it doesn’t change.

    Lastly, let’s say you have 2 mutable references. This would make it possible to have a data race, where both references are trying to edit the data at the same time, and end up messing each other up. So Rust says no. You’re only allowed to have one mutable reference at a time.

    As long as your program never breaks these few rules, you’ve appeased the borrow checker. This is often easier said than done though