Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use num_traits::PrimInt;
- /// this only exists to be able to instantiate the value via `Default::default()`.
- /// It could, however, be useful for adding other methods too.
- trait MyPrimInt: PrimInt + Default {}
- macro_rules! impl_my_prim_int {
- ($($ty:ident)*) => ($(impl MyPrimInt for $ty {})*)
- }
- impl_my_prim_int! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
- trait MakeOne {
- fn make_one() -> Self;
- }
- impl MakeOne for String {
- fn make_one() -> Self {
- String::new()
- }
- }
- impl<T: MyPrimInt> MakeOne for T {
- fn make_one() -> Self {
- Default::default()
- }
- }
- #[derive(Debug)]
- struct TheStruct<T> {
- val: T,
- }
- impl<T: MakeOne> TheStruct<T> {
- fn new() -> Self {
- TheStruct {
- val: T::make_one()
- }
- }
- }
- fn main() {
- let str = TheStruct::<String>::new();
- println!("str = {:?}", str);
- let int = TheStruct::<i16>::new();
- println!("int = {:?}", int);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement