Latest / CyberCode Academy / Course 19 - Ultimate Rust Crash Course | Episode 3: Rust Fundamentals: Mastering Ownership, References, and Borrowing
Transcript
- 0:00Speaker 1: Welcome back to the deep dive, where we break down
- 0:02Speaker 1: complex tech topics to give you the insights you need.
- 0:05Speaker 2: Today, we're talking about something that is really the heart
- 0:08Speaker 2: and soul of Rust.
- 0:10Speaker 1: We are we're talking about its secret weapon, the principle
- 0:12Speaker 1: of ownership.
- 0:13Speaker 2: And if you've ever worked in SEA or C plus
- 0:16Speaker 2: plus game, you know the pain. You allocate memory, you
- 0:18Speaker 2: forget to free it boom a memory leak.
- 0:21Speaker 1: Or worse, you free it too early and now you're
- 0:23Speaker 1: chasing some impossible define dangling pointer bug. It's a nightmare exactly.
- 0:28Speaker 2: Russ just says, no, we're not going to do that.
- 0:30Speaker 1: Yeah.
- 0:31Speaker 2: And ownership is how it makes that promise. It's a
- 0:34Speaker 2: total shift in how you manage memory.
- 0:36Speaker 1: Okay, so that's a huge claim, guaranteed memory safety without
- 0:39Speaker 1: a garbage collector.
- 0:40Speaker 2: Yeah.
- 0:41Speaker 1: So for you, our mission for this deep dive is
- 0:44Speaker 1: to really unpack that, right.
- 0:45Speaker 2: We need to get into the three rules of ownership,
- 0:47Speaker 2: understand how data actually moves around your program, and then
- 0:51Speaker 2: look at this idea of borrowing, which is.
- 0:54Speaker 1: How you can access data without causing all that chaos.
- 0:57Speaker 2: Precisely, this is what lets Rust be as fast as
- 1:00Speaker 2: C plus plus but with safety guarantees you normally only
- 1:03Speaker 2: find in slower managed languages.
- 1:05Speaker 1: All right, let's start at the foundation, then the three
- 1:07Speaker 1: rules that govern everything.
- 1:09Speaker 2: Okay, Rule number one is simple.
- 1:10Speaker 1: Each value in RUSK has a variable that's called its owner.
- 1:13Speaker 2: That's it. One value, one owner. Every piece of data
- 1:17Speaker 2: is accounted for, and.
- 1:18Speaker 1: Rule number two builds directly on that.
- 1:20Speaker 2: It does. There can only be one owner at a time.
- 1:24Speaker 2: This is the big one. This is what prevents so
- 1:26Speaker 2: many concurrency bugs from the get go.
- 1:28Speaker 1: So no two variables can own the same piece of
- 1:32Speaker 1: data simultaneously. You can lend it out, which I guess
- 1:35Speaker 1: is borrowing, but only one can be the true owner exactly.
- 1:38Speaker 2: And that leads to rule number three, which is where
- 1:41Speaker 2: the magic happens for cleanup.
- 1:43Speaker 1: When the owner goes out of scope, the value.
- 1:44Speaker 2: Is dropped immediately.
- 1:45Speaker 1: Wait so just gone. The second of variable leaves its
- 1:49Speaker 1: little block of code. The memory it owns is just
- 1:52Speaker 1: poof reclaimed.
- 1:53Speaker 2: Poof instantly and automatically. It's a concept called our aii
- 1:58Speaker 2: or resource acquisition is initial as it basically means cleanup
- 2:02Speaker 2: is tied to the object's lifetime. It's not optional. You
- 2:05Speaker 2: can't forget, so.
- 2:05Speaker 1: No more manual free or delete calls, the compiler handles it.
- 2:09Speaker 1: Because of this.
- 2:09Speaker 2: Rule, the compiler guarantees it. And just to be clear
- 2:12Speaker 2: about what we mean by value, it often lives in
- 2:15Speaker 2: two places.
- 2:15Speaker 1: Right right, the stack and the heap.
- 2:18Speaker 2: The stack is for your fixed sized data. It's super fast,
- 2:21Speaker 2: last in, first out. The heap is for data that
- 2:24Speaker 2: can grow or shrink, like a string. It's a bit slower.
- 2:28Speaker 1: So for a string, the variable on the stack just
- 2:30Speaker 1: holds a pointer to the actual text on the heap,
- 2:33Speaker 1: plus its length and capacity.
- 2:34Speaker 2: And when that variable on the stack goes out of spope,
- 2:37Speaker 2: rule three kicks in and cleans up both the stack
- 2:40Speaker 2: data and the heap data it points to instantly, no leaks.
- 2:44Speaker 1: Okay, let's see this in action, because this is where
- 2:45Speaker 1: things get interesting. Let's say I create a string S
- 2:48Speaker 1: one yep. Then I create another variable S two, and
- 2:51Speaker 1: I say S two equals S one. In most languages
- 2:54Speaker 1: that would be.
- 2:54Speaker 2: A copy, but not in rest. This is not a copy.
- 2:57Speaker 2: It's a move.
- 2:58Speaker 1: A move What does that mean?
- 2:59Speaker 2: So, because that string data on the heat could be huge,
- 3:03Speaker 2: Rust avoids an expensive copy by default. Instead, it just
- 3:06Speaker 2: copies the small bit of data on the stack. The
- 3:09Speaker 2: pointer length and capacity.
- 3:11Speaker 1: It copies that from S one over to S two right.
- 3:14Speaker 2: And here's the crucial part. It then immediately invalidates S one.
- 3:18Speaker 2: It just kills it, marks it as uninitialized unusable. If
- 3:22Speaker 2: you try to use S one after that line, the
- 3:25Speaker 2: compiler will stop you with a very clear error use
- 3:29Speaker 2: of moved value.
- 3:30Speaker 1: Wow. Okay, why why is it so aggressive about that?
- 3:33Speaker 2: Think about what would happen if it didn't. Both S
- 3:35Speaker 2: one and S two would be pointing to the exact
- 3:37Speaker 2: same memory on the heat. Okay, when S one goes
- 3:40Speaker 2: out of scope, it would free that memory. Then a
- 3:42Speaker 2: little later, S two goes out of scope and tries
- 3:45Speaker 2: to free the same memory again.
- 3:46Speaker 1: Ah, a double free air a classic catastrophic bug.
- 3:50Speaker 2: And the move prevents that entire class of bug from
- 3:52Speaker 2: ever happening. The compiler enforces it.
- 3:55Speaker 1: That makes so much sense. It sacrifices the original variable
- 3:58Speaker 1: to guarantee memory safety. But what if I actually want
- 4:01Speaker 1: a full deep copy, I'm willing to pay the performance cost.
- 4:03Speaker 2: Then you have to be explicit. You have to call
- 4:05Speaker 2: the clone methods.
- 4:06Speaker 1: So S two is one dot clone exactly.
- 4:08Speaker 2: That tells Russ, Yes, I know this is expensive. Please
- 4:11Speaker 2: allocate new memory on the heap and copy all the
- 4:13Speaker 2: data over. Now you have two completely separate values, each
- 4:17Speaker 2: with its own owner. Rule two is satisfied.
- 4:20Speaker 1: So move is the cheap, safe default. Clone is the
- 4:24Speaker 1: expensive explicit option.
- 4:26Speaker 2: You got it, And the same logic applies when you
- 4:29Speaker 2: pass variables to functions.
- 4:31Speaker 1: If I pass my string S one to a function,
- 4:33Speaker 1: ownership moves into the function.
- 4:36Speaker 2: It moves into the functions parameter. The function now owns it,
- 4:39Speaker 2: and when the function ends, the.
- 4:41Speaker 1: Value is dropped as one is consumed and gone.
- 4:43Speaker 2: Right, which can be really annoying Most of the time.
- 4:46Speaker 2: You just want a function to read your data, not
- 4:49Speaker 2: destroyed it.
- 4:50Speaker 1: Yeah, that seems really clunky. You'd have to have the
- 4:52Speaker 1: function return the value just so you can get ownership back.
- 4:55Speaker 1: There has to be a better way.
- 4:56Speaker 2: There is, and that brings us to the elegant solution. Okay,
- 5:01Speaker 2: instead of giving the function ownership, you just lend it
- 5:03Speaker 2: temporary access.
- 5:04Speaker 1: You give it a reference, and that's the ampersand the
- 5:07Speaker 1: and symbol.
- 5:07Speaker 2: That's the one. When you pass in US one, you're saying, here,
- 5:10Speaker 2: you can look at this, but you don't own it.
- 5:12Speaker 2: Ownership stays with US.
- 5:13Speaker 1: One, and I can use s one again right after
- 5:15Speaker 1: the function call immediately.
- 5:17Speaker 2: And the best part is Rust's compiler uses a system
- 5:20Speaker 2: called lifetimes to make sure that reference can never ever
- 5:24Speaker 2: point to invalid memory. It prevents the use after free bug.
- 5:28Speaker 1: So references let you read data. But what if I
- 5:32Speaker 1: need a function to change my data without taking.
- 5:34Speaker 2: It ah For that, you need a mutable reference. That's
- 5:36Speaker 2: a lot.
- 5:37Speaker 1: So I have to declare my original variable is mutable,
- 5:41Speaker 1: and then I pass a mutable reference to it, and that.
- 5:43Speaker 2: Gives the function temporary right access. It can modify the
- 5:46Speaker 2: data directly.
- 5:47Speaker 1: This is where it gets really interesting, isn't it, Because
- 5:49Speaker 1: this is where the famous borrochecker comes in.
- 5:51Speaker 2: This is the absolute core of Rust's safety guarantees, especially
- 5:55Speaker 2: for concurrency. The borrow checker enforces one single and credibly
- 6:00Speaker 2: important rule, single rule. At any given time, for any
- 6:04Speaker 2: piece of data, you can have either one of two things. Okay,
- 6:07Speaker 2: one exactly one mutable reference that's it, just one writer,
- 6:11Speaker 2: or any number of immutable references as many readers as
- 6:14Speaker 2: you want.
- 6:14Speaker 1: But you can never have both at the same time.
- 6:16Speaker 1: You can't have mutable reference while any immutable ones exist.
- 6:20Speaker 2: Never Why is that so critical?
- 6:22Speaker 1: Well, If you have a bunch of threads reading data,
- 6:24Speaker 1: that's fine, no conflicts. But the second one thread needs
- 6:27Speaker 1: to write.
- 6:28Speaker 2: You have to lock everyone else out. You can't have
- 6:30Speaker 2: someone reading the data while it's halfway through being changed.
- 6:33Speaker 2: They'd get corrupted data. And you certainly can't have two
- 6:36Speaker 2: threads writing to the same spot at once. That's a
- 6:38Speaker 2: data race.
- 6:39Speaker 1: So the borrowchecker is like a compile time mutex. It
- 6:43Speaker 1: prevents data races by its very nature before the code
- 6:46Speaker 1: even runs.
- 6:47Speaker 2: That's the payoff. When you're first learning, you fight the borrochecker.
- 6:51Speaker 2: It feels restrictive, why won't you let me do this?
- 6:54Speaker 1: But then you realize it's not being difficult. It's saving
- 6:57Speaker 1: you from yourself. It's catching those subtle bugs that would
- 7:00Speaker 1: have taken you weeks to debug at runtime.
- 7:02Speaker 2: That's the moment it clicks, when you realize that the
- 7:05Speaker 2: compiler is your partner. If your code compiles, you have
- 7:09Speaker 2: this incredible confidence that it's memory safe.
- 7:11Speaker 1: Let's make this concrete. Let's walk through three common intentions
- 7:15Speaker 1: you might have with a function. First up inspection, I
- 7:18Speaker 1: just want to look at a string, maybe check if
- 7:20Speaker 1: it ends with an S, to see if it's plural.
- 7:22Speaker 1: I don't want to change it or consume it.
- 7:24Speaker 2: Your intention is read only, so the function takes an
- 7:27Speaker 2: immutable reference and ends string.
- 7:29Speaker 1: I pass in my word. The function does its check,
- 7:32Speaker 1: and my original my word variable is totally untouched and
- 7:35Speaker 1: ready to use. Safe, fast, simple, perfect, Okay. Next intention modification.
- 7:41Speaker 1: I have a change function. I want to add an
- 7:43Speaker 1: Z to the end of my word. If it's singular.
- 7:45Speaker 2: Your intention is writing. That requires a mutable reference mut string.
- 7:50Speaker 2: You pass them up my word.
- 7:51Speaker 1: And while that function is running, the borrow checker ensures
- 7:54Speaker 1: nothing else can read or write to my word.
- 7:56Speaker 2: It's locked down exactly. The function makes its change when.
- 8:00Speaker 2: When it's done, the original variable has been updated.
- 8:03Speaker 1: All right, Final intention consumption. I have an eat function.
- 8:06Speaker 1: I wanted to take the string, do some complex work
- 8:08Speaker 1: with it, and then I'm done with it. It should
- 8:10Speaker 1: be destroyed.
- 8:11Speaker 2: Your intention is to give up ownership. The function takes
- 8:14Speaker 2: the string by value no amper sand.
- 8:17Speaker 1: This triggers a move.
- 8:18Speaker 2: The function takes ownership, does its work, and when it returns,
- 8:22Speaker 2: Rule three kicks in and the string's memory is freed.
- 8:25Speaker 2: The original variable is now invalid.
- 8:28Speaker 1: It's so clear, isn't it The function signature tells you
- 8:31Speaker 1: exactly what its relationship with your data is going to be.
- 8:34Speaker 1: Are you just reading it, are you changing it? Or
- 8:36Speaker 1: are you consuming it?
- 8:37Speaker 2: That explicitness is the source of all the safety. You're
- 8:40Speaker 2: forced to be intentional.
- 8:41Speaker 1: So let's do a quick recap. We have ownership, one
- 8:45Speaker 1: owner per value. We have the move semantic as the
- 8:48Speaker 1: default for heap data, with an explicit costly clone if
- 8:52Speaker 1: you need it.
- 8:52Speaker 2: And we have borrowing with either immutable or mutable references
- 8:58Speaker 2: to allow temporary access.
- 9:00Speaker 1: All of which is enforced by the borrow checker. And
- 9:02Speaker 1: it's one writer or many reader's rule to prevent data rases.
- 9:05Speaker 2: And if you connect all that to the bigger picture,
- 9:08Speaker 2: you see the genius of it. Rust moves the entire
- 9:11Speaker 2: burden of memory safety from runtime like a garbage collector
- 9:14Speaker 2: to compile time. You get the performance without sacrificing the safety.
- 9:17Speaker 1: That's a powerful combination which leads us with a final
- 9:20Speaker 1: thought for you to chew on.
- 9:21Speaker 2: Okay, so imagine you create a really big complex data structure,
- 9:25Speaker 2: maybe a list with thousands of items in it. Each
- 9:28Speaker 2: of those items takes up his own memory. Now what
- 9:31Speaker 2: happens if you pass that entire list to a function
- 9:34Speaker 2: by value consuming it. What happens to all the memory
- 9:37Speaker 2: for those thousands of individual items inside, and why is
- 9:40Speaker 2: cleaning all of that up an absolute non issue in rust,
- 9:43Speaker 2: when in a language like C plus plus it could
- 9:45Speaker 2: be a major source of leaks if you're not careful.
- 9:48Speaker 1: The answer is baked right into rule three and that
- 9:51Speaker 1: idea of deterministic destruction. A great thing to think about
- 9:55Speaker 1: it is, that's all the time we have for this
- 9:56Speaker 1: deep dive into ownership and borrowing. We hope you feel
- 9:59Speaker 1: a little more friendly toward the borrow checker now. We'll
- 10:02Speaker 1: catch you next time.