Skip to content

Destructuring

Introduction

Some data structures (namely structures, unions, arrays, slices and tuples) can be destructured, i.e decomposed in inner values stored in new variables.
Destructuring can happen in:

  • let bindings
  • match statements/expressions (see the next page)
  • in the parameter definition of a function.

Simple examples

Structures

boa
struct Point:
    x: i32
    y: i32

// let binding example: 
let point = Point(x=1, y=2)
let Point(x, y) = point

// function parameter example:
fn point_handler(Point(x, y): point):
    // do something with x and y...

Unions

boa
union Point:
    PointInt(x: i32, y: i32)
    PointFloat(x: f32, y: f32)

// let binding example:
let point = PointInt(1, 2)
let PointInt(x, y) = point

// function parameter example:
fn point_handler(PointInt(x, y): Point):
    // do something with x and y...

Arrays and slices

boa
// let binding example:
let point = [1, 2]
let [x, y] = point

// function parameter example:
fn point_handler([x, y]: []i32):
    // do something with x and y...

Tuples

boa
// let binding example:
let point = (1, 2)
let (x, y) = point

// function parameter example:
fn point_handler((x, y): (i32, i32)):
    // do something with x and y

Advanced destructuring patterns

With destructuring statements, it is possible to:

  • Ignore one or more values using _, the discard identifier:

    boa
    let point3d = (1, 2, 3)
    let (x, _, z) = point3d
  • Ignore all the remaining values (or all the remaining values except the last n ones) by writing ...:

    boa
    let hello_tuple = ('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!')
    let (h, e, l1, l2, o, ...) = hello_tuple
    let (..., w, o2, r, l3, d, _) = hello_tuple

    Note that ... can appear at most once in a non-nested destructuring statement.

Recursive destructuring

Destructuring can be done in a recursive way, i.e a destructuring can be arbitrarily nested in another one:

boa
// reusing the struct Point from earlier

let points = (Point(1, 2), Point(3, 4))
let (Point(x1, y1), Point(x2, y2)) = points
// x1 == 1
// y1 == 2
// x2 == 3
// y2 == 4

Destructuring, compilation errors and runtime errors

In case of a wrong destructuring pattern being used (too few values, too many values, wrong union variant), Boa will either raise a compilation error or a runtime error depending of the category of the type being destructured:

  • A compilation error for structures, tuples and arrays since their shape are known at compile-time
  • A runtime error for slices and unions, since the size of a slice and the actual variant stored in a union are only known at runtime.

Note that Boa will always trigger a compilation error if ... appears more than once in a non-nested destructuring statement, whatever the type being destructured is.