Is it possible to define "super" trait which will require to define methods from other traits

Hello Community!

Doubt my question is correct, but I want to ask.
I would like to implement several traits for my structures: for example, serde::Serialize, From<Something> and some of my own traits

Is there any approach that allows me to create one trait that would require to implement both from, serialize and my own methods?

Thank you in advance!

You can define them as supertraits on a new trait:

trait MyTrait: From<Something> + serde::Serialize + ... {}

Any generics with the MyTrait bound will be able to use items from the supertraits:

fn foo<T: MyTrait>(x: Something) -> T {
    T::from(x)
}
1 Like

Depends on what you mean by your question. If you're thinking about some trait

trait Foo {
   fn from(...) -> ...;
   fn serialize(...) -> ...;
   fn more_methods(...) -> ...;
}

where an implementation

impl Foo for MyType {
   fn from(...) -> ... { /* some implementation */ }
   fn serialize(...) -> ... { /* some implementation */ }
   fn more_methods(...) -> ... { /* some implementation */ }
}

will have the effect that MyType automatically also implements From<Something> and serde::Serialize, then no this is not something that Rust can do, (although I'm personally hoping that something like this might eventually become possible).


If instead you mean a trait

trait Foo {
   fn more_methods(...) -> ...;
}

where implementing

impl Foo for MyType {
   fn more_methods(...) -> ... { /* some implementation */ }
}

simply errors, unless you also write some separate

impl From<Something> for MyType {
   fn from(...) -> ... { /* some implementation */ }
}

and

impl serde::Serialize for MyType {
   fn serialize(...) -> ... { /* some implementation */ }
}

then that's what a supertrait bound as suggested above by @Cyborus04 can achieve.


Whether that's useful to you depends on your intended use-case of such a feature; if you could give more context, perhaps that also helps us understanding what exactly you're after. If you just want to have a concise way to implement the same set of traits over and over, for a bunch of structs (which is one application that I can imagine for the first idea I explained above) then currently, you could somewhat do that by defining a macro.

1 Like

Thank you for great explanation!
yeah, supertrait looks good for me as I would like to use generic functions to do some logic

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.