Resources in Arrays and Dictionaries

Arrays and dictionaries behave differently when they contain resources: It is not allowed to index into an array to read an element at a certain index or assign to it, or index into a dictionary to read a value for a certain key or set a value for the key.

Instead, use a swap statement (<->) or shift statement (<- target <-) to replace the accessed resource with another resource.

resource R {}

// Declare a constant for an array of resources.
// Create two resources and move them into the array.
//
let resources <- [
    <-create R(),
    <-create R()
]

// Invalid: Reading an element from a resource array is not allowed.
//
let firstResource <- resources[0]

// Invalid: Setting an element in a resource array is not allowed,
// as it would result in the loss of the current value.
//
resources[0] <- create R()

// Instead, when attempting to either read an element or update an element
// in a resource array, use a swap statement with a variable to replace
// the accessed element.
//
var res <- create R()
resources[0] <-> res
// `resources[0]` now contains the new resource.
// `res` now contains the old resource.

// Use the shift statement to move the new resource into
// the array at the same time that the old resource is being moved out
let oldRes <- resources[0] <- create R()
// The old object still needs to be handled
destroy oldRes

The same applies to dictionaries.

Resources cannot be moved into arrays and dictionaries multiple times, as that would cause a duplication.

Resource arrays and dictionaries can be destroyed.

The variable array functions like append, insert, and remove behave like for non-resource arrays. Note however, that the result of the remove functions must be used.

The variable array function contains is not available, as it is impossible: If the resource can be passed to the contains function, it is by definition not in the array.

The variable array function concat is not available, as it would result in the duplication of resources.

The dictionary functions like insert and remove behave like for non-resource dictionaries. Note however, that the result of these functions must be used.

Last updated

Was this helpful?