What is ownership in Rust?
Ownership in Rust
Section Overview: In this section, the speaker explains what ownership is in Rust and why it exists.
What is Ownership?
- Ownership refers to a variable that is responsible for deleting the data it represents when the variable ends its scope.
- Unlike property rights in real life, ownership confers no benefits to the owner. The owning variable doesn’t have preferential access to the data it owns nor can it prevent others from accessing what is owned.
- Rust needs to know when it’s safe to delete data since there’s no garbage collector like other programming languages such as Java or Python. This leads to ownership being used instead.
⭐️How Ownership Works
- Rust only allows a single owner, so when an owner leaves scope or becomes invalid, it must be safe to delete the owned data.
- To create an owner, you create a value and bind it to a variable. Once you’ve created the data, you create an owner.
- We can transfer ownership in Rust through moving or copying semantics. Moving transfers ownership while copying duplicates the data and creates two owners.
- When we transfer ownership through assignment, only the new name can be used since ownership has moved there.
- Another way of transferring ownership is by moving into a function.
Why Ownership Exists
- Ownership exists because Rust does not have a garbage collector like other programming languages such as Java or Python. Including one would impose runtime costs and make performance less predictable by introducing latency and pauses.
Passing Variables to Functions
Section Overview: This section discusses how variables are passed into functions in Rust.
Ownership and the End of a Variable’s Life Cycle
- When an owner’s scope ends or becomes invalid, any resources it owns are deleted.
- Data is deleted when there is no owner for it.
For Loops and Ownership Transfer
- Ownership transfers into a loop, making the variable inaccessible after the loop finishes.
- Looping over references does not move ownership; ownership stays where it was.
- If you have a reference to the variable or a mutable reference, you can still access the variable after the loop has finished.
⭐️String Literals and No Owner
- String literals behave differently because they don’t actually own the data that they refer to. They are kept alive for the whole program.
- Variables of string literals have the type
&str
, which is a reference to a string slice.
Conclusion
Section Overview: This section concludes the talk on ownership in Rust.
- The speaker hopes that viewers enjoyed the talk and encourages them to ask questions in the comments.
- The book “Rust in Action” explains ownership in depth, and viewers can use a discount code provided by the speaker to purchase it.
Generated by Video Highlight
https://videohighlight.com/video/summary/1mq-vV5ECOo