Skip to content

Problem with GAT and HRTB #90729

Closed
Closed
@davidli2010

Description

@davidli2010

I tried this code:

#![feature(generic_associated_types)]

use std::marker::PhantomData;

pub trait Type {
    type Ref<'a>;
}

pub trait AsBytes {
    fn as_bytes(&self) -> &[u8];
}

impl AsBytes for &str {
    fn as_bytes(&self) -> &[u8] {
        (*self).as_bytes()
    }
}

pub struct Utf8;

impl Type for Utf8 {
    type Ref<'a> = &'a str;
}

pub struct Bytes<T: Type> {
    _marker: PhantomData<T>,
}

impl<T: Type> Bytes<T>
where
    for<'a> T::Ref<'a>: AsBytes,
{
    pub fn new() -> Self {
        Self {
            _marker: PhantomData,
        }
    }
}

fn main() {
    let _b = Bytes::<Utf8>::new();
}

I expected to see this happen: I had expected compilation to succeed

Instead, this happened: Compilation fails with the error message below.

error[E0277]: the trait bound `for<'a> <Utf8 as Type>::Ref<'a>: AsBytes` is not satisfied
  --> src\main.rs:41:14
   |
41 |     let _b = Bytes::<Utf8>::new();
   |              ^^^^^^^^^^^^^^^^^^ the trait `for<'a> AsBytes` is not implemented for `<Utf8 as Type>::Ref<'a>`
   |
note: required by `Bytes::<T>::new`
  --> src\main.rs:33:5
   |
33 |     pub fn new() -> Self {
   |     ^^^^^^^^^^^^^^^^^^^^
help: consider further restricting the associated type
   |
40 | fn main() where for<'a> <Utf8 as Type>::Ref<'a>: AsBytes {
   |           ++++++++++++++++++++++++++++++++++++++++++++++

Meta

rustc --version --verbose:

rustc 1.58.0-nightly (e269e6bf4 2021-10-26)
binary: rustc
commit-hash: e269e6bf47f40c9046cd44ab787881d700099252
commit-date: 2021-10-26
host: x86_64-pc-windows-msvc
release: 1.58.0-nightly
LLVM version: 13.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-GATsArea: Generic associated types (GATs)C-bugCategory: This is a bug.F-generic_associated_types`#![feature(generic_associated_types)]` a.k.a. GATs

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions