Variable lifetime basics
๐ Scenario: Imagine you have a small box where you keep a note. You want to understand how long the note stays in the box before it disappears. In Rust, this idea is called variable lifetime. It helps us know when a piece of data is still usable and when it is gone.
๐ฏ Goal: You will create a simple Rust program that shows how a variable's lifetime works. You will declare a variable, use it inside a smaller box (a block), and then try to use it outside to see what happens.
๐ What You'll Learn
Create a variable called
message with the value "Hello, Rust!"Create a new block using curly braces
{ }Inside the block, create a variable called
inner_message that borrows messagePrint
inner_message inside the blockTry to print
inner_message outside the block (commented out to avoid error)๐ก Why This Matters
๐ Real World
Understanding variable lifetimes helps prevent bugs related to using data that no longer exists. This is important in programs that manage memory carefully, like games or system tools.
๐ผ Career
Rust developers must understand lifetimes to write safe and efficient code, especially when working with references and borrowing.
Progress0 / 4 steps