E0301_ARRAY_DESTRUCTURING_WRONG_NUMBER_OF_ELEMENTS

Constant E0301_ARRAY_DESTRUCTURING_WRONG_NUMBER_OF_ELEMENTS 

Source
pub const E0301_ARRAY_DESTRUCTURING_WRONG_NUMBER_OF_ELEMENTS: ErrorCode;
Expand description

§E0301: Array destructuring pattern did not fit array length

This error occurs when an array destructuring pattern does not match the number of elements in the array.

Array destructuring in Compose requires that:

  1. If the pattern does not use .., the number of bindings must exactly match the array’s length.
  2. If the pattern uses a .. (rest) binding, the array must have at least as many elements as the non-rest bindings.

Violating these rules results in a length mismatch error.


§Too many elements in the array, pattern without ..
let [a, b] = [1, 2, 3];
// autogenerated
  • Pattern binds 2 elements.
  • Array has 3 elements.
  • Error: the pattern does not account for all elements.

Fix: Use .. to ignore or capture the remaining elements:

let [a, b, ..] = [1, 2, 3];       // ignore remaining
let [a, b, ..rest] = [1, 2, 3];   // capture remaining

§Case 2: Too few elements in the array, pattern without ..
let [a, b, c] = [1, 2];
// autogenerated
  • Pattern binds 3 elements.
  • Array has only 2 elements.
  • Error: not enough elements to satisfy the pattern.

Fix: Provide an array with enough elements:

let [a, b, c] = [1, 2, 3];  

§Case 3: Unknown-length array, pattern without ..
# let get_array = { => [1, 2, 3] };
let arr = get_array();
let [a, b] = arr;
// autogenerated
  • The compiler cannot know the length of arr at compile time.
  • Error: exact-length destructuring is not allowed for unknown-length arrays.

Fix: Use .. to allow variable-length arrays:

# let arr = [1, 2, 3];
let [a, b, ..] = arr;  

§Case 4: Too few elements when using a ..rest binding
let [a, b, ..c] = [1];
// autogenerated
  • Pattern requires 2 non-rest elements (a and b).
  • Array has only 1 element.
  • Error: not enough elements to bind all required non-rest values.

Fix: Ensure the array has at least as many elements as the non-rest bindings:

let [a, b, ..c] = [1, 2];  

or reduce the number of non-rest bindings:

let [a, ..c] = [1];