【发布时间】: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。我将为第二个问题开一个新的。