pallet-boxesDestructuring

Unpack structs and arrays into variables with defaults, nesting, and rest captures.

circle-info

Since BoxLang 1.12.x

Destructuring lets you unpack values from structs and arrays into variables in a single expression.

It works in declarations like var and in assignments.

📋 Table of Contents

🧩 Struct destructuring

Struct destructuring binds keys by name.

user = { name: "Luis", role: "admin" }
var { name, role } = user

println( name )
println( role )

You can also rename keys while destructuring.

While renaming a struct key, you can also place it into a different scope. (You may not use the var, final, or static keywords in these cases.)

📚 Array destructuring

Array destructuring binds values by position.

This also works with assignments.

📝 Declarations vs assignments

Declarations work directly with var, final, or static.

Non-declaration struct assignments must be wrapped in parentheses.

Array assignments do not need the extra parentheses.

circle-info

Use parentheses for struct assignments unless you are declaring with var, final, or static.

🎯 Defaults

Defaults let you provide a fallback when a value is not available.

Struct defaults

Struct defaults apply when a key is missing.

Array defaults

Array defaults apply when a slot is missing or null.

🪆 Nested patterns

You can destructure nested structs and arrays.

Nested structs

Nested arrays

You can combine nesting with defaults.

🧺 Rest bindings

Rest bindings capture the remaining values.

Struct rest

Array rest

Array destructuring also supports middle rest.

Short arrays still bind predictably.

circle-exclamation

🎯 Scoped targets

You can explicitly destructure into scopes by renaming the binding target.

This is useful when you want the source key and target variable to differ.

circle-exclamation

⚠️ Common errors

Invalid shorthand keys

Some keys cannot use shorthand.

Use explicit renaming for quoted keys, spaced keys, or numeric keys.

Wrong source type

Struct destructuring expects a struct-like value. Array destructuring expects an array-like value.

If a nested value does not match the pattern, BoxLang throws an error.

Multiple rest bindings

A destructuring pattern can only contain one rest binding.

Safer target syntax

Scoped targets must start with an explicit scope. Use variables.foo, request.bar, or another real scope.

✅ Summary

Destructuring gives you:

  • concise assignments

  • built-in renaming

  • defaults

  • nested extraction

  • rest capture

  • scoped targets when needed

Last updated

Was this helpful?