Lesson 19 of 21 · Types
Traits
A trait names methods that a type can have. An impl block gives the methods to one type. A method has self as its first parameter, and a call is shape.area().dyn Shape is a value of any type with an impl of Shape. So one list can hold a Rect and a Triangle, and each item uses the method of its own type.Traits and impl blocks are valid only in a .surfs file. A file that calls a method of a trait imports the trait.Your turn
- In App.surf, add Triangle { base: 4.0, height: 3.0 } to the list. The compiler shows an error, because Triangle has no impl of Shape.
- In shapes.surfs, add this impl under the impl for Rect:
- impl Shape for Triangle { fn area(self) -> Float = self.base * self.height / 2.0; }
- The total is 12 now.
Preview
1 error
The sandbox needs a browser.