November 2017
Beginner
308 pages
8h 32m
English
In this example, we will create a trait that will contain the signature for two functions: calc_perimeter and calc_area. To start with, we construct a struct. In this case, we will have two structs:
struct Perimeter { side_one: i32, side_two: i32, }struct Oval { radius: f32, height: f32,}
We need to create a trait for each. The general format for a trait looks like this:
trait TraitName { fn function_name(&self) -> return_type; }
In our case, we would have the following:
trait CalcPerimeter{ fn calc_perimeter(&self) -> i32; }trait CalcArea { fn calc_area(&self) -> f32; }
We now need to create an implementation for both of these traits. The impl, though, will not look quite the same.
Before, we had the following:
Read now
Unlock full access