Files
sx/examples/32-optionals.sx
2026-02-22 22:16:30 +02:00

98 lines
2.2 KiB
Plaintext

#import "modules/std.sx";
// --- Type declarations ---
OptNode :: struct { value: s32; next: ?s32; }
OptInner :: struct { val: s32; }
OptOuter :: struct { inner: ?OptInner; }
// --- Comptime optionals ---
ct_sum :: () -> s32 {
x: ?s32 = 42;
y: ?s32 = null;
return (x ?? 0) + (y ?? 99);
}
CT_RESULT :: #run ct_sum();
main :: () -> s32 {
// Basic optional creation
x: ?s32 = 42;
y: ?s32 = null;
print("x = {}\n", x);
print("y = {}\n", y);
// Force unwrap
print("x! = {}\n", x!);
// Null coalescing
print("x ?? 0 = {}\n", x ?? 0);
print("y ?? 99 = {}\n", y ?? 99);
// If-binding (safe unwrap)
if val := x {
print("if-bind x: {}\n", val);
}
if val := y {
print("should not print\n");
} else {
print("if-bind y: none\n");
}
// Pattern matching
check :: (v: ?s32) -> s32 {
return if v == {
case .some: (val) { val; }
case .none: { 0; }
};
}
print("match some: {}\n", check(42));
print("match none: {}\n", check(null));
// Optional chaining
p: ?OptNode = OptNode.{ value = 10, next = 20 };
q: ?OptNode = null;
print("p?.value = {}\n", p?.value ?? 0);
print("q?.value = {}\n", q?.value ?? 0);
// Deep chaining
o1 := OptOuter.{ inner = OptInner.{ val = 99 } };
o2 := OptOuter.{ inner = null };
print("o1.inner?.val = {}\n", o1.inner?.val ?? 0);
print("o2.inner?.val = {}\n", o2.inner?.val ?? 0);
// Flow-sensitive narrowing
a: ?s32 = 10;
b: ?s32 = 20;
if a != null {
print("narrowed a: {}\n", a);
}
// Guard narrowing
guard :: (v: ?s32) -> s32 {
if v == null { return 0; }
return v;
}
print("guard 42: {}\n", guard(42));
print("guard null: {}\n", guard(null));
// Compound narrowing
if a != null and b != null {
print("both: {} {}\n", a, b);
}
// Compound guard
guard2 :: (a: ?s32, b: ?s32) -> s32 {
if a == null or b == null { return 0; }
return a + b;
}
print("guard2: {}\n", guard2(3, 4));
// Struct field defaults
n := OptNode.{ value = 10 };
print("default next: {}\n", n.next);
// Comptime result
print("comptime: {}\n", CT_RESULT);
return 0;
}