Files
corelang/examples/arrays_and_slices.kl

53 lines
1.5 KiB
Plaintext

/*
Static arrays are exactly like c arrays, difference is
we can easily then get a slice of that array.
Slices are static arrays + length, they simplify array handling.
This allows us to pass an array into a function easily, then that function
can still access that length information easily.
Passing a pointer to array + length is a common pattern in C. So it would
be nice if handling of that was simplified.
*/
main :: (): int
static_array: [8]int
// We can get size of array using length_of builtin
#Assert(length_of(static_array) == 8)
// Accessing values is like in C
// Variables are zeroed by default
Assert(static_array[1] == 0)
element2 := static_array[2]
element0: int = static_array[0]
Assert(element0 == 0 && element2 == 0)
// We can loop through arrays
// this implicitly defines 'it' variable
for static_array
*it = 1
// We set all variables to 1 so
Assert(static_array[6] == 1)
// This is how slice is defined, no [] index in between brackets
// slice is array pointer + length
// Other then that it works exactly like regular array
slice: []int = static_array
// We can't do a compile time Assert anymore
Assert(length_of(slice) == 8)
Assert(slice[4] == 1)
// After we loop and reassign slice values
// old static_array gets changed
//
// In this example, operator ';;' is used
// it inserts a new line, allows to write this
// example in a single line
for slice;; *it = 2
Assert(static_array[2] == 2)