Skip to content

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!

@wekauwau
Copy link

It's clearly stated that the lifetime of return value is connected to the lifetime of contents. query's lifetime isn't connected in any way to the lifetime of return value, that's why its lifetime didn't get annotated. Refer to Chap. 10.3

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.

2 participants