Implement trait for type's value


I would like to do following definition which is not supported by the language.

impl Zero for 0u8 {}

Would this make sense to be added to the language?

Best regards,


It seems not possible for new use.

suppose that we wrote let mut x=0u8;, then, how could we perform Zero over x?

What happened if we modify x later?

Discussion above shows that, we could not make "Runtime trait" for such type x. You could only perform such dance with const values.

For now, const_generics is already a stable feature.

struct X<const N:usize>();
trait Zero{fn out(self)->u8 where Self: Sized{0}} // better code could be written, but I'm lazy
trait One{fn out(self)->u8 where Self: Sized{1}}
impl Zero for X<0>{}
impl One for X<1>{}
fn main(){
    let a=X::<0>();
    println!("{} {}",a.out(),X::<1>().out())

This sounds a lot like pattern types.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.