Skip to content

Inherent async fn returning Self treats type's lifetime parameters as 'static #61949

Closed
@Arnavion

Description

@Arnavion

rustc 1.37.0-nightly (2887008e0 2019-06-12) and playground's 2019-06-17 b25ee644971a168287ee

Playground

#![feature(async_await)]

pub struct Foo<'a> {
    pub bar: &'a i32,
}

impl<'a> Foo<'a> {
    pub async fn new(bar: &'a i32) -> Self {
        Foo {
            bar
        }
    }
}
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
 --> src/lib.rs:8:22
  |
8 |     pub async fn new(bar: &'a i32) -> Self {
  |                      ^^^
  |
note: first, the lifetime cannot outlive the lifetime 'a as defined on the impl at 7:6...
 --> src/lib.rs:7:6
  |
7 | impl<'a> Foo<'a> {
  |      ^^
  = note: ...so that the expression is assignable:
          expected &i32
             found &'a i32
  = note: but, the lifetime must be valid for the static lifetime...
  = note: ...so that the types are compatible:
          expected Foo<'_>
             found Foo<'static>

It works to either change the signature to take bar: &'static i32, or to change the body of the fn to use a static borrow like bar: &5. So the compiler really does want the function to return a Foo<'static>, even though Self is a Foo<'a>


The workaround is to not use Self:

-    pub async fn new(bar: &'a i32) -> Self {
+    pub async fn new(bar: &'a i32) -> Foo<'a> {

Mentoring notes: See notes here on Zulip.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-async-awaitArea: Async & AwaitAsyncAwait-TriagedAsync-await issues that have been triaged during a working group meeting.C-bugCategory: This is a bug.P-mediumMedium priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions