import std::io; # A constant holds views of another constant's array, which it shares rather # than copies: a view of a view, views within a struct and within memory the # constant allocated, an empty view at the array's end, and a reference to an # element. const primes: u64[5] = [2, 3, 5, 7, 11]; const all: span = primes[:]; const middle: span = primes[1:3]; const inner: span = rest(middle); const none: span = primes[5:0]; const largest: &u64 = &primes[4]; const words: strview[3] = ["one", "two", "three"]; const later: span = words[1:]; struct table { var name: strview; var rows: span; } const odd: table = table{ name = "odd", rows = primes[1:] }; def rest(of: span): span { return of.sub(1, of.length - 1) else { return of; }; } def halves(): span> { val made := raw_allocate(2 * size_of::>()) as *mut span; made[0] = primes[0:2]; made[1] = primes[2:3]; return span::>::over(made as *span, 2); } const split: span> = halves(); def sum(of: span): u64 { var total := 0u; for each in of { total += each; } return total; } def main(): void { println($"{all.length} {sum(all)} {middle[0]} {middle[2]} {inner[0]} {inner.length} {none.length}"); println($"{later[0]} {later[1]} {later.length}"); println($"{odd.name} {odd.rows.length} {sum(odd.rows)}"); println($"{split.length} {sum(split[0])} {sum(split[1])}"); # The views are of the array itself, not of copies of it. println($"{all.data == primes[:].data} {inner.data == primes[2:].data} {split[1].data == primes[2:].data} {none.data == primes[5:0].data}"); # A reference to an element, as a constant and as the program runs, is to # the element where the array is. val held: &u64 = &primes[4]; println($"{largest} {(largest as *u64) == all.data + 4} {(held as *u64) == all.data + 4}"); # A local constant views a global one. const first: span = primes[1:2]; println($"{sum(first)} {first.data == all.data + 1}"); }