Why is the `'a` in `Box<dyn std::any::Any +'a>` required to satisfy `'a:'static`?

fn use_a<'a>(v:&'a i32)->Box<dyn std::any::Any + 'a>{
    Box::new(0)
}
fn main(){
  let cc = 0;
  use_a(&cc);
}

The compiler reports an error

cc does not live long enough, ..., argument requires that cc is borrowed for 'static

The super-trait of Any is 'static. So, there are two issues here.

  1. What lifetime does the trait object should satisfy? T:'a, T:'static, or T:'a + 'static?
  2. Why is the lifetime 'a in the function signature required to satisfy 'a:'static?

Deletion for my incorrect explanation :frowning:

However, I didn't require that 'a:'static, so, why does v need to outlive 'static? I found a relevant issue opened for Rust Reference Default trait object lifetimes section is quite inaccurate · Issue #1407 · rust-lang/reference · GitHub, the issue mentioned a similar case, and the interpretation may be relevant here

Trait bounds introduce implied bounds on the trait object lifetime

pub trait LifetimeTrait<'a, 'b>: 'a {}

fn fp<'a, 'b, 'c>(t: Box<dyn LifetimeTrait<'a, 'b> + 'c>) {
    // This compiles which indicates an implied `'c: 'a` bound
    let c: &'c [()] = &[];
    let _: &'a [()] = c;
}

I just didn't find the formal document about this.

What is the purpose of 'b here, rather than simply not including it?

Yeah, so this is a gray zone in trait objects from the linked issue...

Your case is also like

When there are trait bounds, the bounds always implicitly apply to the trait object lifetime, whether that bound is elided, the wildcard '_, or explicitly annotated. In particular, if the trait has a 'static bound, the trait object lifetime is effectively always 'static. This is considered unambiguous even if there are other lifetime bounds (in contrast with type bounds).

Therefore, when a trait has a 'static bound, irregardless of anything else

  • The default is effectively 'static (even when technically inferred or another lifetime parameter)
1 Like

Introduce another lifetime parameter that is irrelevant to 'a, which is effectively a 'static.

So, the suggested wording interprets that, for the case

trait MyTrait:'static{}
fn show<'a>(_:&'a ())-> Arc<dyn MyTrait + 'a>{}

The implied trait bound is 'a:'static?

All three. (The middle one implies the other two.)

Yep.

1 Like

The implied trait bound is 'a:'static?

Yep.

I found the interpretation in your posted issue for Rust Reference of this undocumented part😀.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.