-
Notifications
You must be signed in to change notification settings - Fork 12.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unnecessary lifetime error #109591
Comments
This is a known unfortunate limitation of impl Trait design. See #82171. The solution you proposed is sadly not applicable if the hidden type contains associated type projections. Consider this example where the trait Trait {
type Assoc: 'static;
}
fn get<T: Trait>(val: T::Assoc) -> impl std::any::Any + 'static {
val
} Consider closing it in favor of #82171. |
Okay! Thank you! Any idea why creating a |
Continuing from the previous example, using type DynTrait = dyn Any + 'static; // not generic over T.
type ImplTrait<T> = impl Any + 'static = <T as Trait>::Assoc; // generic over T. It is the same reason that this is rejected: use std::any::Any;
fn into_any<T: 'static>(t: T) -> impl Any {
t
}
fn main() {
let _ = [into_any(0u8), into_any(0u16)];
} While |
I see! Thank you for your time |
The following code produces a compiler error:
playground
The reason, as I see it, is that according to RFC 1951, a returned
impl
captures generic arguments. However, in this case, I do have a lifetime bound'a
which is present on the returnedimpl
but not on the genericT
. However, the function still acts as ifT
has a lifetime bound of'a
.Okay, so if the returned
impl
capturesT
, then I would expect to be able to useT
in the return value. But the compiler will not let me:playground
The compiler will not let me use
T
in the returnedimpl
, but still, it requires thatT
is borrowed for'a
.I would expect one of two things to happen:
impl
capturesT
, which would allow me to useT
in the return value.impl
does not captureT
, in which case it would be possible forT
to not have lifetime'a
.Instead what happens is that the inner function does not allow the
impl
to captureT
, but the outer function acts as if theimpl
has capturedT
.An additional note
I noticed that by wrapping the returned value in a
Box<dyn _>
, the code compiles:playground
This further leads me to believe that this lifetime error is unnecessary. Without any modification to the inner function, the compiler now understands that the returned
impl
in fact does not captureT
.Solution
Because of the
'a
bound on the returnedimpl
, the inner function does not allow the returnedimpl
to captureT
. The functionouter
should therefore be able to know that the parameterT
does not have to live for'a
. Therefore, it should be possible to remove the lifetime error in the first code example, at this playground.The text was updated successfully, but these errors were encountered: