0
0
Rustprogramming~15 mins

Variable lifetime basics in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
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 message
Print inner_message inside the block
Try 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
1
Create a variable called message
Create a variable called message and set it to the string "Hello, Rust!".
Rust
Need a hint?

Use let message = "Hello, Rust!"; to create the variable.

2
Create a new block and borrow message
Inside the main function, create a new block using { }. Inside this block, create a variable called inner_message that borrows message using &message.
Rust
Need a hint?

Use { } to create a block and let inner_message = &message; to borrow.

3
Print inner_message inside the block
Inside the block where inner_message is declared, add a println! statement to print inner_message.
Rust
Need a hint?

Use println!("{}", inner_message); to print the borrowed message.

4
Try to print inner_message outside the block (commented out)
After the block, add a commented line that tries to print inner_message using println!("{}", inner_message);. This shows that inner_message is not available outside its block.
Rust
Need a hint?

Use // to comment out the line println!("{}", inner_message);.