When is it useful for a bound constant to use a lifetime other than "static"?

RFC 1623 , stabilized in Rust 1.17.0, made it so that we do not need to explicitly specify a lifetime 'staticin staticor const:

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

RFC 195 defined related constants that were stabilized in Rust 1.20.0:

struct A;

impl A {
    const B: i32 = 42;
}

When trying to combine these two, an error occurs:

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

GitHub related issue # 38831 contains a comment

We decided against this, because in this case there may be other lives that you want. For example:

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

, , , . , , 'static - , .

'static? 'static?

+6
1

, :

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
}

, , , .

+4

All Articles