Resources
Resources are types that can only exist in one location at a time and must be used exactly once.
Resources must be created (instantiated) by using the create keyword.
At the end of a function which has resources (variables, constants, parameters) in scope, the resources must be either moved or destroyed.
They are moved when used as an initial value for a constant or variable, when assigned to a different variable, when passed as an argument to a function, and when returned from a function.
Resources can be explicitly destroyed using the destroy keyword.
Accessing a field or calling a function of a resource does not move or destroy it.
When the resource is moved, the constant or variable that referred to the resource before the move becomes invalid. An invalid resource cannot be used again.
To make the usage and behaviour of resource types explicit, the prefix @ must be used in type annotations of variable or constant declarations, parameters, and return types.
To make moves of resources explicit, the move operator <- must be used when the resource is the initial value of a constant or variable, when it is moved to a different variable, when it is moved to a function as an argument, and when it is returned from a function.
// Declare a resource named `SomeResource`, with a variable integer field.
//
pub resource SomeResource {
pub var value: Int
init(value: Int) {
self.value = value
}
}
// Declare a constant with value of resource type `SomeResource`.
//
let a: @SomeResource <- create SomeResource(value: 0)
// *Move* the resource value to a new constant.
//
let b <- a
// Invalid: Cannot use constant `a` anymore as the resource that it referred to
// was moved to constant `b`.
//
a.value
// Constant `b` owns the resource.
//
b.value // equals 0
// Declare a function which accepts a resource.
//
// The parameter has a resource type, so the type annotation must be prefixed with `@`.
//
pub fun use(resource: @SomeResource) {
// ...
}
// Call function `use` and move the resource into it.
//
use(resource: <-b)
// Invalid: Cannot use constant `b` anymore as the resource
// it referred to was moved into function `use`.
//
b.valueA resource object cannot go out of scope and be dynamically lost. The program must either explicitly destroy it or move it to another context.
To make it explicit that the type is a resource type and must follow the rules associated with resources, it must be prefixed with @ in all type annotations, e.g. for variable declarations, parameters, or return types.
Resources must be used exactly once.
Last updated
Was this helpful?