首页 > 解决方案 > Rust 中的重复 trait 方法实现

问题描述

在下面的代码中, 和 的实现show_author()是一样PostPostDraft

是否可以对其进行去重并直接在特征中或以其他形式实现它,以便不必编写两次?

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
    }
}

当试图用 trait 中的实际实现替换方法签名时,会显示以下错误,表明 trait 显然不知道(并且正确地知道)任何author字段:

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

在假设的故意无效的假想 Rust 代码中,解决方案是简单地同时声明两个structs 的实现:

impl PostAuthor for Post, PostDraft {
    fn show_author(&self) -> String {
        &self.author
    }
}

标签: rusttraits

解决方案


推荐阅读