0
0
Rustprogramming~30 mins

Lifetimes in functions in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Lifetimes in Functions
📖 Scenario: Imagine you are writing a program that manages book titles in a library. You want to write a function that takes two book title references and returns the title that comes first alphabetically. To do this safely in Rust, you need to understand how lifetimes work in functions.
🎯 Goal: Build a Rust function that takes two string slice references with lifetimes and returns the reference to the title that comes first alphabetically.
📋 What You'll Learn
Create two string slice references with exact values
Declare a lifetime parameter for the function
Write a function that returns the reference with the smaller alphabetical order
Print the result of calling the function with the two titles
💡 Why This Matters
🌍 Real World
Lifetimes are important in Rust programs that handle references to data without copying, such as managing text data or configuration settings safely.
💼 Career
Understanding lifetimes is essential for Rust developers to write safe and efficient code, especially in systems programming, web servers, and embedded software.
Progress0 / 4 steps
1
Create two book title string slices
Create two string slice variables called title1 and title2 with the exact values "Rust Programming" and "Advanced Rust" respectively.
Rust
Hint

Use let to create variables and assign string slices with double quotes.

2
Declare a lifetime parameter for the function
Write the start of a function called first_alphabetical that takes two string slice references input1 and input2 with the same lifetime 'a and returns a string slice reference with lifetime 'a. Just write the function signature line ending with an opening brace {.
Rust
Hint

Use fn function_name<'a>(param1: &'a str, param2: &'a str) -> &'a str syntax.

3
Implement the function logic to return the first alphabetical title
Inside the first_alphabetical function, write an if statement that compares input1 and input2 using <. Return input1 if it is smaller, otherwise return input2. Close the function with a closing brace }.
Rust
Hint

Use if input1 < input2 { return input1; } else { return input2; } style.

4
Call the function and print the result
Call the first_alphabetical function with title1 and title2 as arguments, store the result in a variable called first_title, and then print first_title using println!.
Rust
Hint

Use let first_title = first_alphabetical(title1, title2); and println!("{}", first_title);.