Is it possible to define a macro that can add default implementations of functions for a impl block ?
ie something like
macro_rules! ElementImpl {
($tr: ident, $method: ident) => {
// Here I would output the trait implementation but with the added get_name($self) method
};
}
pub trait Element {
fn get_name(&self) -> String;
}
pub struct Export {
first_name: String
}
ElementImpl! {
impl Element for Export {
fn another_implentation(&self) -> String {
}
}
}
So at the end the Element impl for Export would contain the functions get_name and another_implentation.
Thanks
kornel:
impl Element for Export {}
I tried that just before asking funny enough. On Rust playground nightly I get
24 | impl Element for Export {
| ----------------------- first implementation here
...
31 | impl Element for Export {
| ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Export`
kornel
August 16, 2018, 10:12am
4
Yeah, sorry, I mixed it up with the regular impl
block. The impl for Trait
is limited to one
(If I understood correctly your question)
You can't add a method in a trait impl that is not part of the trait itself: ex
If what you want is having a default impl of some methods of the trait you can do this
The problem was
I have quite a few methods of the Element trait that have to be implemented for hundreds of types. Easy things like
fn get_element_name() -> &'static str {
stringify!("CounterSourceElement")
}
I have a macro that can generate these type of methods in the objects I am implementing Element for ie
element! {
CounterSourceElement {
}
}
But I would like some way to reduce having to implement them in the impl trait code where I need them to be ie
impl Element for CounterSourceElement {
fn get_element_name() -> &'static str {
stringify!("CounterSourceElement")
}
.....
}
for every new element type.
Hope that makes sense.
In the end I defined the trait for Element to be
pub trait Element: ElementMethods
I then used the macro to create the ElementMethods impl wile leaving the user to define the methods in Element.