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.
What lifetime does the trait object should satisfy? T:'a
, T:'static
, or T:'a + 'static
?
Why is the lifetime 'a
in the function signature required to satisfy 'a:'static
?
vague
April 16, 2024, 8:19am
2
Deletion for my incorrect explanation
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.
chung
April 16, 2024, 8:57am
4
What is the purpose of 'b
here, rather than simply not including it?
vague
April 16, 2024, 9:24am
5
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
vague
April 16, 2024, 9:27am
6
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
?
xmh0511:
What lifetime does the trait object should satisfy? T:'a
, T:'static
, or T:'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😀.
system
Closed
July 16, 2024, 1:11am
10
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.