Struct with trait bounds definition

If I want to define a structure to hold only data types with specific trait bounds, do I need to define trait bounds for both struct itself and its impl? I met this investigating sources of the volatile_register crate.

pub struct RO<T>
    where T: Copy
{
    register: VolatileCell<T>,
}

impl<T> RO<T>
    where T: Copy
{
    #[inline(always)]
    pub fn read(&self) -> T {
        self.register.get()
    }
}

As I understand it, impl cannot go by itself, so probably it's enough to specify trait bounds only for the struct (or enum, or whatever impl is for)?

If you have trait bounds on the struct, you also need the same (or more restrictive) bounds on the impl:

struct Test<T>(T)
where
    T: Copy;

// works fine
impl<T> Test<T> where T: Copy {}

// compile error!
impl<T> Test<T> {}

The opposite is not true, however!

struct Test<T>(T);

// works fine - impl will only apply in cases where T is Copy
impl<T> Test<T> where T: Copy {}

// also works fine - impl will always apply!
impl<T> Test<T> {}

Well, looks reasonable. Thank you

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