Skip to content

Clarify lifetimes in search function in chapter 12.4 #4448

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

zimka1
Copy link

@zimka1 zimka1 commented Jul 18, 2025

This PR updates the search function signature in chapter 12.4 to explicitly declare two lifetimes: one for the query parameter and one for the contents parameter.

Original code:

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str>

Updated code:

pub fn search<'a, 'b>(query: &'a str, contents: &'b str) -> Vec<&'b str>

Why this change?

While the original function signature compiles correctly, it may be confusing to beginners. Using a single lifetime parameter can suggest that both query and contents must live for the same duration, even though the return value depends only on contents.

According to the first lifetime elision rule, as written in Chapter 10:

The first rule is that the compiler assigns a lifetime parameter to each parameter that’s a reference.
In other words, a function with one parameter gets one lifetime parameter:
fn foo<'a>(x: &'a i32);
a function with two parameters gets two separate lifetime parameters:
fn foo<'a, 'b>(x: &'a i32, y: &'b i32);
and so on.

To make this explicit, the revised version introduces two separate lifetimes — 'a and 'b. This highlights that the input references are independent, and clearly shows that the return value is tied only to contents.

This adjustment improves clarity and aligns more closely with how lifetimes are explained earlier in the book. It helps prevent misconceptions and builds a more accurate mental model for new readers.

Let me know if you'd like any revisions — happy to adjust!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant