Skip to content

[GAT] Associated type lifetime on regular type #87735

Closed
@c410-f3r

Description

@c410-f3r

After playing with Generic Associated Types, the following snippet was successfully created:

#![feature(generic_associated_types)]

pub trait AsRef2 {
  type Output<'a> where Self: 'a;

  fn as_ref2<'a>(&'a self) -> Self::Output<'a>;
}

impl<T> AsRef2 for Vec<T> {
  type Output<'a> where Self: 'a = &'a [T];

  fn as_ref2<'a>(&'a self) -> Self::Output<'a> {
    &self[..]
  }
}

#[derive(Debug)]
struct Foo<T>(T);
#[derive(Debug)]
struct FooRef<'a, U>(&'a [U]);

impl<U> AsRef2 for Foo<Vec<U>> {
  type Output<'a> where Self: 'a = FooRef<'a, U>;

  fn as_ref2<'a>(&'a self) -> Self::Output<'a> {
    FooRef(self.0.as_ref2())
  }
}

fn main() {
    let foo = Foo(vec![1, 2, 3]);
    dbg!(foo.as_ref2());
}

But then I was wondering if it is possible to generalize the above statement for every Foo<T> with T: AsRef2. Here is what was accomplished so far:

#![feature(generic_associated_types)]

pub trait AsRef2 {
  type Output<'a> where Self: 'a;

  fn as_ref2<'a>(&'a self) -> Self::Output<'a>;
}

impl<T> AsRef2 for Vec<T> {
  type Output<'a> where Self: 'a = &'a [T];

  fn as_ref2<'a>(&'a self) -> Self::Output<'a> {
    &self[..]
  }
}

#[derive(Debug)]
struct Foo<T>(T);
#[derive(Debug)]
struct FooRef<'a, U>(&'a [U]);

impl<'b, T, U> AsRef2 for Foo<T>
where
    // * `for<'b, 'c> T: AsRef2<Output<'b> = &'c [U]>>` does not work
    //
    // * `U` is unconstrained but should be allowed in this context because `Output` is
    // an associated type
    T: AsRef2<Output<'b> = &'b [U]>,
    U: 'b
{
  type Output<'a> where Self: 'a = FooRef<'a, U>;

  fn as_ref2<'a>(&'a self) -> Self::Output<'a> {
    FooRef(self.0.as_ref2())
  }
}

fn main() {
    let foo = Foo(vec![1, 2, 3]);
    dbg!(foo.as_ref2());
}

Any clues? Feel free to close this issue if duplicated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-GATsArea: Generic associated types (GATs)F-generic_associated_types`#![feature(generic_associated_types)]` a.k.a. GATsGATs-triagedIssues using the `generic_associated_types` feature that have been triagedS-bug-has-testStatus: This bug is tracked inside the repo by a `known-bug` test.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions