Files
sakurac/tests/programs/trait_composition_1.sakura
T
2026-11-19 04:54:17 -06:00

32 lines
992 B
Plaintext

import std::io;
trait named {
def tag(&this): string { return "t"; }
def name(&this): string;
def greet(&this): string { return $"hi {this.name()}"; }
}
trait sized {
def name(&this): string;
var width: i64 { get; set; }
}
trait shape: sized, named {
def describe(&this): string { return $"{this.greet()} {this.width}"; }
}
struct box: shape { var w: i64; }
def box::name(&this): string { return "box"; }
var box::width: i64 { get => this.w; set => this.w = value; }
struct dot {}
def dot::name(&this): string { return "dot"; }
var dot::width: i64 { get => 0; set {} }
def render(s: &mut shape): string { s.width = s.width + 1; return s.describe(); }
def only_named(n: &named): string { return n.greet(); }
def only_sized(z: &sized): i64 { return z.width; }
def main(): void {
var b := box{ w = 4 };
var d := dot{};
println(render(&mut b));
println(render(&mut d));
println(b.describe());
val s: &shape = &b;
println($"{only_named(s)} {only_sized(s)} {s.tag()}");
}