Arrays
Cocolang provides support for fixed size containers using arrays. A collections is assumed to be an array if the size of the container is pre-defined at declaration.
var arr = [3]U64{1, 2, 3}
Here arr is initialized with an array of size 3, hence a maximum of 3 values can only be stored in the array.
The size of an array can never be changed and merging arrays is not allowed.
Arrays can be sliced by using the colon operator to extract elements between the 2 indices such as in arr[2:3]
.
If you omit indices, Coco automatically sets them to the minimum and maximum possible values.
Inclusivity checks can be called ‘?’ sign.
var check = vrr[2]?
In this check is set with a boolean value depending on whether the index 2 is within total size.
Varrays
Varrays are used of collections of unknown size. Varrays can be be grown and merged as they are not initialized with any fixed size.
var vrr1 []U64
vrr1 is initialized as a varray since there is no size parameter set when initializing the varray.
The merge
function can be called to add the values of the second varray to the first.
The append
function is called to increment the size of the varray while setting a value to it simultaneously.
Slicing works the same way in varrays similar to arrays.
Inclusivity check works similarly in varrays it depends on whether the index has been initialized.
Membership check with ?
operator
To check if an array has an element, one can use the “has” operator ? that returns a boolean “true” if the element exists.
var exists = arr[3]?
coco Collections
endpoint invokable TestArray() -> (res1 [3]U64, res2 [3]U64, length U256):
var arr = [3]U64{1, 2, 3}
arr2 = make([3]U64)
arr2 = [3]U64{2, 3, 4}
return (res1: arr, res2:arr2, length: len(arr))
endpoint invokable TestVarray() ->(res1 []U64, res2 []U64, output Bool, length U256, joined []U64):
var vrr1 []U64
vrr1 = append(vrr1, 1)
vrr1 = append(vrr1,2)
var vrr2 = make([]U64, 2)
vrr2 = append(vrr2, 2)
vrr2 = append(vrr2, 3)
var check = vrr2[1]?
var s = len(vrr2)
var merged = merge(vrr1, vrr2)
return (res1:vrr1 , res2:vrr2, output: check, length: s, joined: merged)