rustfmt icon indicating copy to clipboard operation
rustfmt copied to clipboard

Cannot handle generic associated type with `where` statement

Open ArcticLampyrid opened this issue 1 year ago • 6 comments

For code:

pub trait Foo {
    type Bar
    where
        Self: Sized;
}

impl Foo for u8 {
    // note: there is a space between `u16` and LineFeed
    type Bar = u16 
    where Self: Sized;
}

I got the error:

$ cargo fmt
error[internal]: left behind trailing whitespace
 --> \\?\D:\foo\src\a.rs:9:9:19
  |
9 |     type Bar = u16 
  |                   ^
  |

warning: rustfmt has failed to format. See previous 1 errors.

ArcticLampyrid avatar Aug 10 '24 20:08 ArcticLampyrid

just wondering, is

type Bar = u16 
    where Self: Sized;

really the right syntax?

johnhuichen avatar Aug 11 '24 09:08 johnhuichen

@johnhuichen I did not check any RFC documents, but I believe it is one type of GATs. It works on rustc 1.70, with no build error or runtime error.

ArcticLampyrid avatar Aug 12 '24 05:08 ArcticLampyrid

I am just thinking that where Self:Sized tells trait not to implement Type Bar if it's not sized.

Since you already declared the type, does it still make sense to have where Self:Size in the implementation?

johnhuichen avatar Aug 12 '24 16:08 johnhuichen

@ArcticLampyrid this one should be addressed once we merge https://github.com/rust-lang/rustfmt/pull/5887, which we're planning to do in the near future.

@johnhuichen yes it's the correct syntax and it relates to https://github.com/rust-lang/rust/issues/89122. Also, see the type alias docs of the rust reference.

ytmimi avatar Aug 12 '24 16:08 ytmimi

@ArcticLampyrid this one should be addressed once we merge #5887, which we're planning to do in the near future.

@johnhuichen yes it's the correct syntax and it relates to rust-lang/rust#89122. Also, see the type alias docs of the rust reference.

Thanks! I see what's going on now. I think the where Self: Sized in impl block is allowed but not necessarily needed

johnhuichen avatar Aug 13 '24 01:08 johnhuichen

Thanks! I see what's going on now. I think the where Self: Sized in impl block is allowed but not necessarily needed

It is not code in the real world, it's just a test case.

A more practical usage is:

impl<A> Foo<A> for MyType<A> {
    type Bar = u16 
    where
        A: Sized;
}

ArcticLampyrid avatar Aug 13 '24 06:08 ArcticLampyrid