Rust中的重复特征方法实现

时间:2018-05-07 22:08:27

标签: rust traits

在以下代码中,show_author()Post的{​​{1}}实现相同。

是否可以将其重复删除并直接以特征或其他形式实施,以便不必写两次?

PostDraft

当尝试将方法签名替换为特征中的实际实现时,会显示以下错误,表明特征显然不知道(并且正确地)任何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 } } 字段:

author

在假设有目的无效的虚构Rust代码中,解决方案是简单地一次声明两个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 的实现:

struct

0 个答案:

没有答案