Files
sakurac/tests/programs/default_trait_methods_1.sakura
T

32 lines
1.3 KiB
Plaintext
Raw Normal View History

2026-10-26 10:14:11 -05:00
import std::io;
trait Shape {
def area(&this): f64;
def name(&this): string { return "shape"; }
def describe(&this): string { return $"{this.name()} of area {this.area()}"; }
def grow(&mut this, by: f64): void { this.scale(by); this.scale(by); }
def mix(&this, a: f64, label: span<u8>, other: &Shape): string { return $"{label}{this.area() + a + other.area()}"; }
def scale(&mut this, by: f64): void;
}
struct square: Shape { var side: f64; }
def square::area(&this): f64 { return this.side * this.side; }
def square::scale(&mut this, by: f64): void { this.side *= by; }
struct circle: Shape { var r: f64; }
def circle::area(&this): f64 { return 3 * this.r * this.r; }
def circle::name(&this): string { return "circle"; }
def circle::scale(&mut this, by: f64): void { this.r *= by; }
struct blob { var size: f64; }
def blob::area(&this): f64 { return this.size; }
def blob::scale(&mut this, by: f64): void { this.size += by; }
def show(s: &Shape): string { return s.describe(); }
def enlarge(s: &mut Shape): void { s.grow(2); }
def main(): void {
var sq := square{ 2 };
var c := circle{ 1 };
var b := blob{ 5 };
println($"{sq.describe()}, {c.describe()}, {show(b)}");
sq.grow(3);
enlarge(c);
enlarge(b);
val label := "=";
println($"{sq.side} {c.r} {b.size} {sq.mix(1, label, c)}");
}