Skip to content

GAT/extended: wrong lifetime analysis #113721

Closed as not planned
Closed as not planned
@dhardy

Description

@dhardy

Using generic_associated_types_extended (#95451), this code fails:

#![feature(generic_associated_types_extended)]

trait Trait {
    type Ret<'r> where Self: 'r;
    fn get<'r>(&'r self) -> Self::Ret<'r>;
}

struct Person<'a> {
    name: &'a str,
    age: u16,
}

impl<'a> Trait for Person<'a> {
    type Ret<'r> = (&'r str, u16) where Self: 'r;
    fn get(&self) -> (&str, u16) {
        (self.name, self.age)
    }
}

fn a(p: &Person) {
    let (name, age) = p.get();
    println!("Hello, {name} (age = {age})!");
}

fn b(p: &dyn for<'r> Trait<Ret<'r> = (&'r str, u16)>) {
    let (name, age) = p.get();
    println!("Hello, {name} (age = {age})!");
}

fn main() {
    let name = "Andrew";
    let p = Person { name: &name, age: 6 };
    a(&p);
    b(&p);
}

with error:

error[E0521]: borrowed data escapes outside of function
  --> src/main.rs:26:23
   |
25 | fn b(p: &dyn for<'r> Trait<Ret<'r> = (&'r str, u16)>) {
   |      -  - let's call the lifetime of this reference `'1`
   |      |
   |      `p` is a reference that is only valid in the function body
26 |     let (name, age) = p.get();
   |                       ^^^^^^^
   |                       |
   |                       `p` escapes the function body here
   |                       argument requires that `'1` must outlive `'static`
   |
   = note: due to current limitations in the borrow checker, this implies a `'static` lifetime

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-GATsArea: Generic associated types (GATs)A-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.F-generic_associated_types_extended`#![feature(generic_associated_types_extended)]`T-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