0
0
Rustprogramming~20 mins

Lifetime elision rules in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Lifetime Elision Rules in Rust
📖 Scenario: You are writing a simple Rust program that works with string slices. Rust uses lifetimes to make sure references are valid. Lifetime elision rules help Rust guess lifetimes so you don't have to write them all the time.In this project, you will create a function that returns the longer of two string slices. You will see how Rust applies lifetime elision rules to make your code simpler and safe.
🎯 Goal: Build a Rust function called longer_string that takes two string slices and returns the longer one. Use lifetime elision rules so you don't have to write explicit lifetime annotations.
📋 What You'll Learn
Create two string slices with exact values
Write a function longer_string that takes two string slices as parameters
Use lifetime elision rules by NOT writing explicit lifetime annotations
Return the longer string slice from the function
Print the result of calling longer_string with the two slices
💡 Why This Matters
🌍 Real World
Rust programs often use references to avoid copying data. Understanding lifetime elision helps write safe and clean code when working with references.
💼 Career
Many Rust jobs require knowledge of lifetimes to manage memory safely without garbage collection. This project builds foundational skills for writing reliable Rust code.
Progress0 / 4 steps
1
Create two string slices
Create two string slices called string1 with value "hello" and string2 with value "world!".
Rust
Hint

Use let to create string slices with double quotes.

2
Write the longer_string function without explicit lifetimes
Write a function called longer_string that takes two parameters: x and y, both of type &str. Return the longer string slice. Do NOT write explicit lifetime annotations; rely on Rust's lifetime elision rules.
Rust
Hint

Write the function header with parameters x: &str and y: &str. Return type is &str. Use an if statement to compare lengths.

3
Call the function with the two string slices
Create a variable called result and assign it the value returned by calling longer_string with string1 and string2 as arguments.
Rust
Hint

Call longer_string with string1 and string2. Store the return value in result.

4
Print the result
Write a println! macro call to print the value of result.
Rust
Hint

Use println!("{}", result); to print the string slice stored in result.