How to do it...

Perform the following steps:

  1. Create a file named trait.rs and enter the following code in the script:
        use std::{f64};
fn main() {
// variable of circle data type
let mut circle1 = Circle {
r : 10.0
};
println!("Area of circle {}", circle1.area() );

// variable of rectangle data type
let mut rect = Rectangle {
h:10.0,b : 10.0
};
println!("Area of rectangle {}", rect.area() );
}
  1. Create a struct named Rectangle with the parameters h and b, both 64-bit float data types:
        // userdefined data type rectangle
struct Rectangle {
h: f64,
b: f64,
}
  1. Create a struct named Circle with the parameter r, which is a 64-bit float data type:
        // userdefined data type circle
struct Circle {
r: f64,
}
  1. Create a trait named HasArea with the area functionality:
        // create a functionality for the data types 
trait HasArea {
fn area(&self) -> f64;
}
  1. Define the area function for the Circle user-defined data type:
        // implement area for circle
impl HasArea for Circle {
fn area(&self) -> f64 {
3.14 * (self.r *self.r)
}
}
  1. Define the area function for the Rectangle user-defined data type:
        // implement area for rectangle
impl HasArea for Rectangle {
fn area(&self) -> f64 {
self.h *self.b
}
}

You should get the following output upon running the preceding code:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.183.210