In the following code, the implementation of show_author()
is the same for Post
and PostDraft
.
Is it possible to de-duplicate it and implement it directly in the trait, or in another form, so that it wouldn't have to be written twice?
trait PostAuthor {
fn show_author(&self) -> String;
}
struct Post {
author: String,
}
struct PostDraft {
author: String,
}
impl PostAuthor for Post {
fn show_author(&self) -> String {
&self.author
}
}
impl PostAuthor for PostDraft {
fn show_author(&self) -> String {
&self.author
}
}
When trying to replace the method signature with the actual implementation in the trait, the following error shows, indicating that the trait obviously doesn't know (and rightly so) about any author
field:
error: attempted to take value of method `author` on type `&Self`
--> src/lib.rs:5:15
|
5 | &self.author
| ^^^^^^
|
= help: maybe a `()` to call it is missing? If not, try an anonymous function
In a hypothetical purposefully-invalid imaginary Rust code, a solution would be to simply declare the implementation for the two struct
s at once:
impl PostAuthor for Post, PostDraft {
fn show_author(&self) -> String {
&self.author
}
}