How to add different types

enum A and struct B, I wanna those two can be added to each other.
because they are different types, so I create a common trait named C and impl for both.
but still compile error, , warns: "the size for values of type .... cannot be known at compilation time the trait "SIZED" is not implement for ....";

I have another way to achieve this goal by creating

 impl From< A> for B

to convert A to B advanced and then add them, but takes two steps,
I want to know is it possible to do so, directly add those two by impl Add for them ?

#[derive(Debug)]
enum A{
    I32(i32),
}

#[derive(Debug)]
struct B{
    name:String,
    data: Vec<i32>
}

trait C{}
impl C for A{}
impl C for B{}

impl std::ops::Add for dyn C{
    type Output = B;
    fn add(self, rhs: Self) -> Self::Output {
        // ????
    }
}

fn main(){
    let a = A::I32(20);
    let b = B { name: "test".to_string(), data: vec![1,2,3]};
    let c = a + b;   // c = { name: "test".to_string(), data: vec![21,22,23]};
}

Trait objects don't have a compile-time known size. You have to use a pointer with them.

You don't need to define new traits. std::ops::Add has a defaulted parameter for the “right-hand side” of the addition, that you can specify explicitly to define addition between two different types.

impl std::ops::Add<B> for A {
    type Output = B;
    fn add(self, rhs: B) -> Self::Output { todo!() }
}
impl std::ops::Add<A> for B {
    type Output = B;
    fn add(self, rhs: A) -> Self::Output { todo!() }
}
5 Likes