40 lines
1.5 KiB
Plaintext
40 lines
1.5 KiB
Plaintext
import std::io;
|
|
|
|
# A `maybe` of a reference, a trait reference, or a function value is no larger
|
|
# than what it holds: a null one is `none`.
|
|
trait named { def name(&this): strview; }
|
|
struct cat : named { var lives: u8; }
|
|
def cat::name(&this): strview { return "cat"; }
|
|
|
|
struct link { var value: u64; var next: maybe<&link>; }
|
|
|
|
def find(items: span<u64>, wanted: u64): maybe<&u64> {
|
|
for &x in items { return &x if x == wanted; }
|
|
return nothing {};
|
|
}
|
|
|
|
def main(): void {
|
|
print($"{size_of::<maybe<&u64>>() == size_of::<&u64>()} ");
|
|
print($"{size_of::<maybe<&named>>() == size_of::<&named>()} ");
|
|
print($"{size_of::<maybe<def(u64): u64>>() == size_of::<def(u64): u64>()} ");
|
|
print($"{size_of::<maybe<u64>>() > size_of::<u64>()} ");
|
|
val items: span<u64> = [3, 1, 4];
|
|
if find(items, 4) is some(r) { print($"found {r} "); }
|
|
print($"{find(items, 9) is some(_)} {find(items, 1) else &items[0]} ");
|
|
val third := link { value = 3, next = nothing {} };
|
|
val second := link { value = 2, next = &third };
|
|
var at: maybe<&link> = link { value = 1, next = &second }.next;
|
|
var sum: u64 = 0;
|
|
while at is some(l) { sum += l.value; at = l.next; }
|
|
print($"{sum} ");
|
|
val c := cat { lives = 9 };
|
|
var pet: maybe<&named> = &c;
|
|
if pet is some(p) { print($"{p.name()} "); }
|
|
pet = nothing {};
|
|
print($"{pet is some(_)} ");
|
|
var f: maybe<def(u64): u64> = def(v: u64): u64 => v * 3;
|
|
if f is some(g) { print($"{g(4)} "); }
|
|
f = nothing {};
|
|
match f { none => println("none"); some(g) => println($"{g(1)}"); }
|
|
}
|