trait Greeter { fn greet(self, msg: string); fn shout(self); } struct Robot { id: int; } impl Greeter for Robot { fn greet(self, msg: string) { println "Robot {self.id} says: {msg}"; } fn shout(self) { println "ROBOT {self.id} ACTIVATED"; } } trait Shape { fn area(self) -> float; fn name(self) -> string; } struct Circle { radius: float; } impl Shape for Circle { fn area(self) -> float { return 3.14159 * self.radius * self.radius; } fn name(self) -> string { return "Circle"; } } struct Rectangle { width: float; height: float; } impl Shape for Rectangle { fn area(self) -> float { return self.width * self.height; } fn name(self) -> string { return "Rectangle"; } } @derive(Debug, Clone, Eq) struct Point { x: int; y: int; } fn print_shape_info(s: Shape) { println "Shape: {s.name()}, Area: {s.area()}"; } test "basic_traits" { let r: Robot = Robot { id: 42 }; let g: Greeter = &r; g.greet("Hello World"); g.shout(); } test "advanced_traits" { let c = Circle { radius: 5.0 }; let r = Rectangle { width: 4.0, height: 6.0 }; let s_c: Shape = &c; let s_r: Shape = &r; print_shape_info(s_c); print_shape_info(s_r); if (s_c.area() > s_r.area()) { println "Circle is larger"; } else { println "Rectangle is larger"; } } test "test_derive" { let p1 = Point{x: 10, y: 20}; // Debug let s = p1.to_string(); assert(strcmp(s, "Point { ... }") == 0, "Debug string matches"); // Clone let p2 = p1.clone(); assert(p2.x == 10, "Clone x matches"); // Eq assert(p1.eq(&p2) == true, "Eq works (true)"); let p3 = Point{x: 10, y: 21}; assert(p1.eq(&p3) == false, "Eq works (false)"); } test "implicit_trait_cast" { let c = Circle { radius: 10.0 }; // This previously required explicit casting: print_shape_info((Shape)(&c)); print_shape_info(&c); let r = Rectangle { width: 5.0, height: 5.0 }; print_shape_info(&r); } let g_def_circle = Circle { radius: 2.0 }; fn print_default_shape(s: Shape = &g_def_circle) { println "Default Shape: {s.name()}"; } test "implicit_trait_cast_default" { print_default_shape(); } trait UnderscoreTest { fn method_with_underscores_123(self) -> int; } struct UnderscoreStruct { val: int; } impl UnderscoreTest for UnderscoreStruct { fn method_with_underscores_123(self) -> int { return self.val; } } test "trait_underscores" { let u = UnderscoreStruct { val: 100 }; let t: UnderscoreTest = &u; assert(t.method_with_underscores_123() == 100, "Method with underscores call failed"); }