Here’s a function that prints the area of a geometric shape, and the function takes the type as parameter that can calculate the area of the shape, such as Circle, Triangle, Square, and it needs to use generics and generic constraints.

trait Area {
    fn area(&self) -> f64;
    fn name(&self) -> &str;
}

struct Circle {
    radius: f64,
}

impl Area for Circle {
   fn area(&self) -> f64 {
        std::f64::consts::PI * self.radius * self.radius
    }   
    fn name(&self) -> &str {
        "circle"
    }
}

struct Triangle {
    base: f64,
    height: f64,
}

impl Area for Triangle {
    fn area(&self) -> f64 {
        self.base * self.height * 0.5
    } 
    fn name(&self) -> &str {
        "triangle"
    }
}

struct Square {
    side: f64,
}

impl Area for Square {
    fn area(&self) -> f64 {
        self.side * self.side 
    }
    fn name(&self) -> &str {
        "square"
    }
}

fn print_area<T: Area>(shape: T) {
    println!("The {} area is {}", shape.name(),shape.area());
}

fn main() {
    let circle = Circle {radius: 1.5};
    let triangle = Triangle {base: 2.2, height: 3.3};
    let square = Square {side: 4.0};
    
    print_area(circle);
    print_area(triangle);
    print_area(square);
}
Scroll to Top