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

29 lines
1.1 KiB
Plaintext

import std::io;
# A constant a trait gives a value is a default, which a type naming the trait
# and giving none of its own takes, worked out for that type, with `self` the
# type and the trait's parameters its arguments, as a default method is. A type
# giving its own keeps it, and one satisfying the trait only by its shape gives
# each constant itself.
trait sized<T> { const n: u64 = size_of::<T>() + size_of::<self>(); }
trait named { const name := "unnamed"; const count: u64 = 2; }
struct wide : sized<u32>, named { var a: u64; }
struct thin : sized<u8>, named { var a: u8; }
const thin::name := "thin";
struct shaped { var b: u8; }
const shaped::name := "shaped";
const shaped::count: u64 = 3;
def total<T, U>(): u64 where T: sized<U> { return T::n; }
def name_of<T>(): strview where T: named { return T::name; }
def buffer<T>(): u64 where T: named {
var held: u8[T::count];
return held.length;
}
def main(): void {
println($"{total::<wide, u32>()} {total::<thin, u8>()} {wide::n} {thin::n}");
println($"{name_of::<wide>()} {name_of::<thin>()} {name_of::<shaped>()} {wide::name}");
println($"{buffer::<wide>()} {buffer::<shaped>()}");
}