当特征所需的状态比结构中包含的状态更多时,如何实现结构的特征?例如,如何为下面所示的Employee
结构实现Human
特性?
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
特性,这是唯一的选择吗?
我的背景是在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解决这个问题的方法吗?
发布于 2019-02-25 08:51:03
您几乎可以准确地翻译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
}
}
注意,您仍然需要跟踪name
的生存期,因为&str
是一个引用。如果您将其创建为一个拥有的String
,那么您将不需要Human
的生存期参数,但是Human
不能是Copy
。这是因为String
不能安全地复制到内存中,因为它们的Drop
驱动(类似于C#终结器),如果Rust允许您这样做,就会导致双重自由--这就是为什么没有。
https://stackoverflow.com/questions/54870420
复制相似问题