Impl for '_ vs impl for concrete lifetimes

⚓ Rust    📅 2026-01-07    👤 surdeus    👁️ 1      

surdeus

Is there a style guideline for writing impl X<'_> { fn f<'a>() -> X<'a> { ... } } versus impl X<'a> { fn f() -> Self { ... } } in Rust? Or is this more than a style choice — do they have different meanings?

Here is the code common to both of those two styles.

use std::borrow::Cow;

struct Response<'content> {
    user: String,
    content: Cow<'content, Content>,
}

#[derive(Clone)]
enum Content {
    Cache(()),
    Fetched(()),
}

fn main() {
    let cache = Content::Cache(());
    let _: Response<'_> = Response::new_with_content_ref("user".to_owned(), &cache);

    let content = Content::Fetched(());
    let _: Response<'static> = Response::new("user".to_owned(), content);
}

Style 1: Write functions with concrete lifetimes inside impl X<'_>.

impl Response<'_> {
    pub fn new(user: String, content: Content) -> Response<'static> {
        Response {
            user,
            content: Cow::Owned(content),
        }
    }

    pub fn new_with_content_ref<'content>(
        user: String,
        content: &'content Content,
    ) -> Response<'content> {
        Response {
            user,
            content: Cow::Borrowed(content),
        }
    }

    // other functions ...
}

Style 2: Write a separate impl for each concrete lifetime.

impl Response<'_> {
    // other functions ...
}

impl Response<'static> {
    pub fn new(user: String, content: Content) -> Self {
        Response {
            user,
            content: Cow::Owned(content),
        }
    }
}

impl<'content> Response<'content> {
    pub fn new_with_content_ref(user: String, content: &'content Content) -> Self {
        Response {
            user,
            content: Cow::Borrowed(content),
        }
    }
}

2 posts - 2 participants

Read full topic

🏷️ Rust_feed