0
0
Rustprogramming~30 mins

Why lifetimes exist in Rust - See It in Action

Choose your learning style9 modes available
Why lifetimes exist
📖 Scenario: Imagine you are writing a program that stores references to parts of a string. You want to make sure these references are always valid while your program runs.
🎯 Goal: Learn why Rust uses lifetimes to keep track of how long references are valid and avoid errors.
📋 What You'll Learn
Create a string variable called text with the value "Hello, Rust!"
Create a reference variable called first_word that points to the first 5 characters of text
Add a lifetime annotation to a function called get_first_word that returns a string slice referencing text
Print the value of first_word to show the result
💡 Why This Matters
🌍 Real World
Lifetimes help Rust programs avoid bugs related to invalid references, which is important in systems programming and safe memory management.
💼 Career
Understanding lifetimes is essential for Rust developers working on performance-critical or safe software, such as embedded systems, web servers, or game engines.
Progress0 / 4 steps
1
Create the initial string variable
Create a variable called text and set it to the string "Hello, Rust!"
Rust
Hint

Use let to create a variable and assign the string value.

2
Create a reference to the first word
Create a variable called first_word that is a string slice referencing the first 5 characters of text
Rust
Hint

Use &text[0..5] to get a slice of the first 5 characters.

3
Add a function with lifetime annotation
Write a function called get_first_word that takes a string slice s with a lifetime 'a and returns a string slice with the same lifetime 'a. Inside, return the first 5 characters of s
Rust
Hint

Use &'a str for the input and output types and return the slice inside the function.

4
Print the result
Call the function get_first_word with text and assign the result to first_word. Then print first_word using println!
Rust
Hint

Use let first_word = get_first_word(text); and then println!("{}", first_word);