【问题标题】:Overload a method using traits [duplicate]使用特征重载方法[重复]
【发布时间】:2017-12-18 01:59:02
【问题描述】:

我正在努力使用 Rust 中涉及多种类型的特征来模拟方法重载。

我会用 C++ 编写

struct PdlDict {
     void update(const string&,const string&, double x) {...}
     void update(const string&,const string&, const string x) {...}
};

然后调用它

 PdlDict d;
 d.update(123.0);
 d.update("foo");

在 Rust 中为这个 PdlDict 结构

pub struct PdlDict {
    pub pdl_items: Vec<PdlItem>,
}
impl PdlDict {
    fn new() -> PdlDict {
        PdlDict {
            pdl_items: Vec::new(),
        }
    }
}

我实现了这个有效的特性

trait UpdatePdl {
    fn update(&self, item: &PdlDict, object_name: &str, name: &str);
}
impl<'a> UpdatePdl for &'a str {
    fn update(&self, item: &PdlDict, object_name: &str, name: &str) {}
}
impl<'a> UpdatePdl for f32 {
    fn update(&self, item: &PdlDict, object_name: &str, name: &str) {}
}

调用感觉不符合人体工程学,因为我必须将要更新的对象作为第一个参数传递:

"bar".update(&pdl, "r", "result");
64.0.update(&pdl, "r", "result");

以惯用的 Rust 方式实现相同语义的更合适的方法是什么?

我怀疑这是特征和模板的组合,但我想不出如何处理。

编辑 注意这个问题不是问如何使用特征实现继承。我已经在这个例子中做到了这一点,它工作得很好。它要求一种以上述风格表达继承的方式

【问题讨论】:

    标签: rust traits


    【解决方案1】:

    IMO,惯用的方式是编写类似您所做的内容,然后添加人体工程学:

    impl PdlDict {
        fn update<T: UpdatePdl>(&self, object_name: &str, name: &str, t: T) {
            t.update(&self, object_name, name)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 2020-08-24
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多