#How to make a wrapper trait that surrounds two other derivable traits

31 messages · Page 1 of 1 (latest)

solid night
#

I want a trait that enforces that two other traits must be met. Those two traits are derivable but Id like my wrapper trait to be derivable as well. What should I do? I want to avoid using macros as best as a I can.

stuck cape
#

making your trait derivable requires a derive macro

solid night
#

All my custom trait is a trait with zero function and just the requirement of self implementing two other traits

stuck cape
#

an alternative to derive macros would be a blanket impl, if you want the trait to always be implemented the same way for any type that has the supertraits

solid night
#
pub trait Syncable: Serialize + for<'a> Deserialize<'a> {}
stuck cape
crisp pumice
#

Ye, this sounds like it wants to be a trait alias, so a blanket impl will do

solid night
#

How do you write a blanket trait?

stuck cape
#

a blanket impl is like ```rs
impl<T> MyTrait for T {}

solid night
#

Would it function the same as what I want?

stuck cape
#

pretty much
any type that implements the other traits will then implement your trait

solid night
#
pub trait Syncable {}
impl<T> Syncable for T where T: Serialize + for<'a> Deserialize<'a> {}

So this ^^^

stuck cape
#

you should probably also have those other traits as supertraits of Syncable

solid night
#

so would this change work and be derivable?

stuck cape
#

no, you would not derive your trait

crisp pumice
stuck cape
#

you wouldn't need to

crisp pumice
#

The trait is now automatically implemented in every possible case where you could derive it

#

It's already implemented

solid night
#

Oh ok

#

Now im getting this

#

the trait bound T: Deserialize<'_> is not satisfied
the trait Deserialize<'_> is not implemented for TrustcClick for full compiler diagnostic
lib.rs(179, 8): required by a bound in bincode::deserialize
convert.rs(15, 98): consider further restricting this bound: + serde::Deserialize<'_>

crisp pumice
solid night
#
/// Converts bytes into an object that implements serde Deserialize
pub fn struct_from_bytes<T>(bytes: &[u8]) -> Result<T, Box<bincode::ErrorKind>> where T: Syncable {
    deserialize(bytes)
}
stuck cape
#

did you add the other traits as supertraits of Syncable?

solid night
#

How?

crisp pumice
solid night
#

Okay now its fixed thanks

#

So whatever functions I add to the syncable trait will be applied to all objects that implement Serialize and De-serialize?

crisp pumice
#

Yup