Define Traits And Implement For Types

Declare a trait with required and default methods, implement it for multiple types, and call it through a generic function bound.

RustData Integrity

Code

rustsnippet
31 lines
// 声明 trait:必需方法 + 可选默认方法
trait Area {
    fn area(&self) -> f64;
    fn label(&self) -> String {
        String::from("shape")
    }
}

struct Rect { w: f64, h: f64 }
struct Circle { r: f64 }

// 为多个类型分别 impl:覆盖默认方法可选
impl Area for Rect {
    fn area(&self) -> f64 { self.w * self.h }
    fn label(&self) -> String { format!("rect {}x{}", self.w, self.h) }
}

impl Area for Circle {
    fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r }
    // label 沿用默认实现
}

// 泛型函数:T: Area 约束接受任何实现 types
fn describe<T: Area>(s: &T) {
    println!("{} -> {:.2}", s.label(), s.area());
}

fn main() {
    describe(&Rect { w: 3.0, h: 4.0 });
    describe(&Circle { r: 1.0 });
}

How it works

Count the functions area, label, describe and main as the entire surface area of Define Traits And Implement For Types.

Using it

Entry signature: fn area(&self) -> f64;

Running the file executes main, which drives describe in order.

Key statements

fn label(&self) -> String { format!("rect {}x{}", self.w, self.h) }
fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r }
fn area(&self) -> f64 { self.w * self.h }

Interactive Tools for This Topic

FAQ

How do you run Define Traits And Implement For Types?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.