![](/img/trans.png)
[英]Is it possible to extend a default method implementation of a trait in a struct?
[英]How do I implement a trait for a struct when the trait requires more state than is contained in the struct?
當特征要求的狀態多於結構所包含的狀態時,如何為該結構實現特征? 例如,如何實現下面顯示的Human
結構的Employee
特性?
struct Human {
name: &str,
}
trait Employee {
fn id(&self) -> i32;
fn name(&self) -> &str;
}
impl Employee for Human {
fn id(&self) -> i32 {
// From where do I get the ID?
}
fn name(&self) -> &str {
self.name
}
}
我沒有看到任何方式掖額外的狀態到impl
或進入特質。
創建包含丟失信息的新HumanToEmployeeAdapter
結構並為新結構實現Employee
特性的唯一選擇嗎?
PS我的背景是C#。 這就是我用這種語言處理的方式:
class Human
{
public string Name { get; }
public Human(string name) { Name = name; }
}
interface IEmployee
{
int Id { get; }
string Name { get; }
}
class HumanToEmployeeAdapter : IEmployee
{
readonly Human _human;
public int Id { get; }
public string Name => _human.Name;
public HumanToEmployeeAdapter(
Human human,
int id)
{
_human = human;
Id = id;
}
}
您會注意到,這是“創建新的HumanToEmployeeAdapter
結構”路徑。 那么,這是Rustaceans解決此問題的方式嗎?
您幾乎可以完全翻譯C#代碼,如下所示:
struct Human<'a> {
name: &'a str,
}
trait Employee {
fn id(&self) -> i32;
fn name(&self) -> &str;
}
struct HumanToEmployeeAdapter<'a> {
human: &'a Human<'a>,
id: i32,
}
impl<'a> HumanToEmployeeAdapter<'a> {
fn new(id: i32, human: &'a Human<'a>) -> Self {
HumanToEmployeeAdapter { id, human }
}
}
impl<'a> Employee for HumanToEmployeeAdapter<'a> {
fn id(&self) -> i32 {
self.id
}
fn name(&self) -> &str {
self.human.name
}
}
如果您可以將Human
類型設置為Copy
(其行為類似於C#值類型 ),則可以通過讓HumanToEmployeeAdapter
擁有Human
類型來簡化事情,這意味着您不必擔心引用的生存期:
#[derive(Copy, Clone)]
struct Human<'a> {
name: &'a str,
}
trait Employee {
fn id(&self) -> i32;
fn name(&self) -> &str;
}
struct HumanToEmployeeAdapter<'a> {
human: Human<'a>,
id: i32,
}
impl<'a> HumanToEmployeeAdapter<'a> {
fn new(id: i32, human: Human<'a>) -> Self {
HumanToEmployeeAdapter { id, human }
}
}
impl<'a> Employee for HumanToEmployeeAdapter<'a> {
fn id(&self) -> i32 {
self.id
}
fn name(&self) -> &str {
self.human.name
}
}
請注意,由於&str
是引用,因此您仍然需要跟蹤name
的生存期。 如果將它做成一個擁有的String
,那么你不需要Human
的生命周期參數,但是Human
不能是Copy
。 這是因為String
不能被安全地復制到內存中,這是由於它們的Drop
impl(類似於C#finalizer ),如果Rust允許您這樣做的話,這將導致double-free,這就是為什么它不這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.