【问题标题】:How to implement multiple traits for a struct without repeating methods?如何在不重复方法的情况下为结构实现多个特征?
【发布时间】:2015-12-14 14:55:17
【问题描述】:

下面的代码运行良好,但我经常重复自己 而且我认为这不是真正的乡村风格。例如,我正在为Square 实现两个特征,这感觉不对!此外,函数coordinate() 在特征和实现中重复。

有没有办法在不经常重复自己的情况下实现这段代码?是否可以实现以下两个特征:

impl BasicInfo && Sides for Square {
    ....
} 

上面的代码不起作用,这只是一个想法。当一个函数可以应用于多个结构时,是否可以在 trait BasicInfo 中只定义一次并访问它。

fn main() {
    let x_1: f64 = 2.5;
    let y_1: f64 = 5.2;
    let radius_1: f64 = 5.5;
    let width_01 = 10.54;

    let circle_01 = Circle { x: x_1, y: y_1, radius: radius_1 };
    let square_01 = Square { x: x_1, y: y_1, width: width_01, sides: 4 };

    println!("circle_01 has an area of {:.3}.", 
        circle_01.area().round());
    println!("{:?}", circle_01);
    println!("The coordinate of circle_01 is {:?}.\n", circle_01.coordinate());
    println!("coordinate of square_01: {:?} has an area of: {} m2 and also has {} sides.", 
        square_01.coordinate(), 
        (square_01.area() * 100.0).round() / 100.0,
        square_01.has_sides() );
}

#[derive(Debug)]
struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

struct Square {
    x: f64,
    y: f64,
    width: f64,
    sides: i32,
}

trait BasicInfo {
    fn area(&self) -> f64;
    // coordinate() is declared here, but not defined. Is it possible to define it here and still be able to access it when I want it.
    fn coordinate(&self) -> (f64, f64);
}

trait Sides {
    fn has_sides(&self) -> i32;
}

impl BasicInfo for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
    // coordinate() gets defined again, and looks like repeating code
    fn coordinate(&self) -> (f64, f64) {
        (self.x, self.y)
    }
}

impl BasicInfo for Square {
    fn area(&self) -> f64 {
        self.width.powf(2.0)
    }
    // coordinate() gets defined again, and looks like repeating code
    fn coordinate(&self) -> (f64, f64) {
        (self.x, self.y)
    }
}

impl Sides for Square {
    fn has_sides(&self) -> i32 {
        self.sides
    }
}

【问题讨论】:

  • 这里有两个问题:(1)一次实现两个特征和(2)一次在多个结构上实现一个特征。标题只匹配 (1),所以我建议为 (2) 打开一个新的专用。 SO 不是论坛,格式不适合多个不相关的问题。
  • @MatthieuM。谢谢你的cmets。我将为第二个问题开一个新的。

标签: rust traits


【解决方案1】:

免责声明:在撰写本文时,有两个问题捆绑在一起,后者与标题不匹配。所以按标题...

是否可以一次实现多个特征?

impl BasicInfo && Sides for Square {
    ....
}

没有。

单独实现它们的开销相对较低,对于更复杂的情况,当需要约束时,可能无法实现,因为您希望为每个特征设置不同类型的约束。

话虽如此,您可能会打开一个 RFC 建议实施,然后让社区/开发人员决定他们是否认为值得实施。

【讨论】:

  • 感谢您的评论,我没有使用带条件的特征,也没有真正考虑过。现在我很担心它
【解决方案2】:

对于您的第二个问题(避免重复 coordinate 的相同实现),我想向您展示基于宏的解决方案。

有趣的是,它给你留下了 3 个特征而不是 2 个,所以它的方向与你的第一个问题完全相反。我想你不可能拥有一切! :)

// factoring out the Coordinates trait from BasicInfo
trait Coordinates {
    fn coordinate(&self) -> (f64, f64);
}

// but we can require implementors of BasicInfo to also impl Coordinates
trait BasicInfo: Coordinates {
    fn area(&self) -> f64;
}

// helper macro to avoid repetition of "basic" impl Coordinates
macro_rules! impl_Coordinates { 
    ($T:ident) => {
        impl Coordinates for $T {
            fn coordinate(&self) -> (f64, f64) { (self.x, self.y) }
        }
    }
}

#[derive(Debug)]
struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

#[derive(Debug)]
struct Square {
    x: f64,
    y: f64,
    width: f64,
    sides: i32,
}

// the macro here will expand to identical implementations
// for Circle and Square. There are also more clever (but a bit
// harder to understand) ways to write the macro, so you can
// just do impl_Coordinates!(Circle, Square, Triangle, OtherShape)
// instead of repeating impl_Coordinates!
impl_Coordinates!(Circle);
impl_Coordinates!(Square);


trait Sides {
    fn has_sides(&self) -> i32;
}

impl BasicInfo for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

impl BasicInfo for Square {
    fn area(&self) -> f64 {
        self.width.powf(2.0)
    }
}

impl Sides for Square {
    fn has_sides(&self) -> i32 {
        self.sides
    }
}

【讨论】:

  • 感谢您向我介绍宏,这有助于避免重复相同的代码。
【解决方案3】:

为一种类型实现多个特征并没有错;事实上,这很常见。

我也不明白你在 trait 和 impl 中重复 coordinate 是什么意思。该函数在 trait 中声明并在 impl 中实现,就像所有其他 trait 函数一样。您的意思是该函数的实现在 Square 和 Circle 实现中是相同的吗?宏会在这方面为您提供帮助,尽管可能有更好的方法。

【讨论】:

  • 塞巴斯蒂安,坐标是指在 impl 和 trait 中定义的 fn coordinate(){ ... }。
  • @user3419211 所以问题是在两个 impls 中定义它?它没有在特征中定义。
  • @SebastianRedl 是的,问题是它在两个 impl 中都定义了,当我删除这两个并且只在 trait BasicInfo 中定义它时,我无法访问它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多