Question about generics and traits

Hello, I'm pretty new to the language, I was wondering if it was possible to do something like this:

pub struct Object<A>
where
    A:Trait
{
    appendix: Option<Box<Object<A>>
}

with the exception that I would like the concrete type associated with the generic type of the Object struct and the one associated with the concrete type of its appendix field to be different; both should implement the Trait trait. Thanks in advance.

This is possible if you use a helper trait.

struct Object<A>
where
    A: MyTrait
{
    value: A,
    appendix: Option<Box<dyn AnyObject>>,
}

trait AnyObject {}
impl<A: MyTrait> AnyObject for Object<A> {}

Of course the helper trait should define and forward any methods you need to call on Object.

1 Like

Thank you for the quick response, but I still can't grasp it, let's consider this:

pub struct Object<A, D>
where
    A: MyTrait1,
    D: MyTrait2,
{
    first_field: Object_Struct<A, D>,
    second_field: Option<Box<Object<A, D>>>, // Here I would like the
                                             // concrete type for "this" D to be different
                                             // from the one of the struct declaration.
}

Would be possible to achieve such thing?

Within this block, the names A and D are just standins for concrete types. You can replace them with any type you like in their place, as long as it satisfies the relevant bounds:

pub struct Object<A, D>
where
    A: MyTrait1,
    D: MyTrait2,
{
    first_field: Object_Struct<A, D>,
    second_field: Option<Box<Object<String, Vec<usize>>>>,
}

impl MyTrait1 for String {}
impl MyTrait2 for Vec<usize> {}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.