When is it useful for an associated constant to use a lifetime other than 'static?
Asked Answered
B

1

7

RFC 1623, stabilized in Rust 1.17.0, made it so that we do not have to explicitly specify the 'static lifetime in a static or const:

const MY_DEFAULT_NAME: &str = "Anna";
//                      ^ Look, ma! No 'static!

RFC 195 defined associated constants, which were stabilized in Rust 1.20.0:

struct A;

impl A {
    const B: i32 = 42;
}

When trying to combine these two, an error is raised:

struct A;

impl A {
    const MY_DEFAULT_NAME: &str = "Anna";
}
error[E0106]: missing lifetime specifier
 --> src/main.rs:4:28
  |
4 |     const MY_DEFAULT_NAME: &str = "Anna";
  |                            ^ expected lifetime parameter

The related GitHub issue #38831 has a comment:

We decided against it because, in that case, there might be other lifetimes you would want. For example:

trait Foo<'a> {
    const T: &'a str;
}

that said, revisiting this explanation, it feel a bit weak, since the value of an associated constant would still have to be all consisting of static data. So it seems like 'static is a pretty good default if you don't say otherwise.

What is an example of an associated constant with a non-'static lifetime? What benefit does providing a non-'static lifetime bring?

Blanc answered 1/10, 2017 at 19:55 Comment(0)
G
5

One might consider a constant that is a function:

trait Foo<'a> {
    const BAR: fn(&Self) -> &'a str;
}

struct MyFoo<'a> {
    x: &'a str,
}

impl<'a> Foo<'a> for MyFoo<'a> {
    const BAR: fn(&Self) -> &'a str = my_bar;
}

fn my_bar<'a>(a: &MyFoo<'a>) -> &'a str {
    &a.x
}

Right now, I can't think of how this would be more beneficial than a method.

Gallipot answered 1/10, 2017 at 20:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.