Arrays

Type-C includes built-in array types as a core feature. This primitive array type is distinct from the standard library's Array type.

Similar to Java arrays, Type-C arrays:

  • Have a fixed size.
  • Use zero-based indexing.
  • Are declared using the [] syntax.
  • Can be initialized using the [] literal or the array keyword.

Declaration and Initialization

You can declare and initialize arrays like this:

Accessing Elements and Properties

You can access elements and retrieve the length of an array:

Array Operations

Type-C arrays support a range of operations, including indexing, slicing, and resizing. Here’s a summary:

Examples

Supported Operations

  • Indexing: Access elements by their index.

    • Syntax: arr[i]
    • Constraints: i must be of type u64.
    • Behavior: Returns the element at index i.
  • Reverse Indexing: Access elements using negative indices.

    • Syntax: arr[-i]
    • Constraints: i must be of type u64.
    • Behavior: Returns the element at index arr.length - i.
  • Index Assignment: Modify elements by their index.

    • Syntax: arr[i] = x
    • Constraints: i must be of type u64.
    • Behavior: Sets the element at index i to x and returns x.
  • Reverse Index Assignment: Modify elements using negative indices.

    • Syntax: arr[-i] = x
    • Constraints: i must be of type u64.
    • Behavior: Sets the element at index arr.length - i to x and returns x.
  • Length: Retrieve the array's length.

    • Syntax: arr.length
    • Behavior: Returns the array length as a u64.
  • Slicing: Extract a subarray.

    • Syntax: arr.slice(start, end)
    • Constraints: start and end must be of type u64.
    • Behavior: Returns a new array containing elements from start (inclusive) to end (exclusive).
  • Extend: Increase the array's size.

    • Syntax: arr.extend(x)
    • Constraints: x must be of type u64.
    • Behavior: Resizes the array to x elements. Returns void.

Notes

  • Fixed Size: Arrays does not automatically grow or shrink. Use extend to resize them (this reallocates memory).
  • Index Bounds: Accessing indices out of bounds will result in an error.
  • Unset Values: Uninitialized array elements are set to zero.
  • Immutable Slicing: Slicing produces a copy of the selected range.

Kudos! Keep reading!