Arrays can be used to hold a dynamic number of values of the same type. Although arrays may not be resized after they were created, they can be created with any length. Just like objects arrays are heap-allocated and referenced, meaning an object may have multiple references to it and can be mutated and accessed from each of them.
To create an array with specific values for each element, you can simply write the values as a list inside of square brackets:
proc main() {
val primes = [2, 3, 5, 7, 11]
}
proc main() {
val greetings = ["Hello!"; 16]
}
To get or set an element of an array at a specific position, write the position (starting at 0) inside of square brackets:
use std::io::println
proc main() {
val primes = [2, 3, 5, 7, 11]
println(primes[0]) // prints '2'
println(primes[2]) // prints '5'
println(primes[4]) // prints '11'
}
use std::io::println
proc main() {
val primes = [2, 3, 5, 7, 11]
println(primes[-1]) // prints '11'
println(primes[-2]) // prints '7'
println(primes[-3]) // prints '5'
}
Just like with strings, length may be used to get the length of an array:
use std::io::println
proc main() {
val primes = [2, 3, 5, 7, 11]
println(length(primes)) // prints '5'
}
Just like with objects, == also compares all items (if the lengths match), and addr_eq may be used to check if the references reference the same array.