Resources

Enables resource-oriented programming on Flow

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.

The Move Operator (<-)

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.

1
// Declare a resource named `SomeResource`, with a variable integer field.
2
//
3
pub resource SomeResource {
4
pub var value: Int
5
6
init(value: Int) {
7
self.value = value
8
}
9
}
10
11
// Declare a constant with value of resource type `SomeResource`.
12
//
13
let a: @SomeResource <- create SomeResource(value: 0)
14
15
// *Move* the resource value to a new constant.
16
//
17
let b <- a
18
19
// Invalid: Cannot use constant `a` anymore as the resource that it referred to
20
// was moved to constant `b`.
21
//
22
a.value
23
24
// Constant `b` owns the resource.
25
//
26
b.value // equals 0
27
28
// Declare a function which accepts a resource.
29
//
30
// The parameter has a resource type, so the type annotation must be prefixed with `@`.
31
//
32
pub fun use(resource: @SomeResource) {
33
// ...
34
}
35
36
// Call function `use` and move the resource into it.
37
//
38
use(resource: <-b)
39
40
// Invalid: Cannot use constant `b` anymore as the resource
41
// it referred to was moved into function `use`.
42
//
43
b.value

A resource object cannot go out of scope and be dynamically lost. The program must either explicitly destroy it or move it to another context.

1
{
2
// Declare another, unrelated value of resource type `SomeResource`.
3
//
4
let c <- create SomeResource(value: 10)
5
6
// Invalid: `c` is not used before the end of the scope, but must be.
7
// It cannot be lost.
8
}
1
// Declare another, unrelated value of resource type `SomeResource`.
2
//
3
let d <- create SomeResource(value: 20)
4
5
// Destroy the resource referred to by constant `d`.
6
//
7
destroy d
8
9
// Invalid: Cannot use constant `d` anymore as the resource
10
// it referred to was destroyed.
11
//
12
d.value

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.

1
// Declare a constant with an explicit type annotation.
2
//
3
// The constant has a resource type, so the type annotation must be prefixed with `@`.
4
//
5
let someResource: @SomeResource <- create SomeResource(value: 5)
6
7
// Declare a function which consumes a resource and destroys it.
8
//
9
// The parameter has a resource type, so the type annotation must be prefixed with `@`.
10
//
11
pub fun use(resource: @SomeResource) {
12
destroy resource
13
}
14
15
// Declare a function which returns a resource.
16
//
17
// The return type is a resource type, so the type annotation must be prefixed with `@`.
18
// The return statement must also use the `<-` operator to make it explicit the resource is moved.
19
//
20
pub fun get(): @SomeResource {
21
let newResource <- create SomeResource()
22
return <-newResource
23
}

Resources must be used exactly once.

1
// Declare a function which consumes a resource but does not use it.
2
// This function is invalid, because it would cause a loss of the resource.
3
//
4
pub fun forgetToUse(resource: @SomeResource) {
5
// Invalid: The resource parameter `resource` is not used, but must be.
6
}
1
// Declare a constant named `res` which has the resource type `SomeResource`.
2
let res <- create SomeResource()
3
4
// Call the function `use` and move the resource `res` into it.
5
use(resource: <-res)
6
7
// Invalid: The resource constant `res` cannot be used again,
8
// as it was moved in the previous function call.
9
//
10
use(resource: <-res)
11
12
// Invalid: The resource constant `res` cannot be used again,
13
// as it was moved in the previous function call.
14
//
15
res.value
1
// Declare a function which has a resource parameter.
2
// This function is invalid, because it does not always use the resource parameter,
3
// which would cause a loss of the resource.
4
//
5
pub fun sometimesDestroy(resource: @SomeResource, destroyResource: Bool) {
6
if destroyResource {
7
destroy resource
8
}
9
// Invalid: The resource parameter `resource` is not always used, but must be.
10
// The destroy statement is not always executed, so at the end of this function
11
// it might have been destroyed or not.
12
}
1
// Declare a function which has a resource parameter.
2
// This function is valid, as it always uses the resource parameter,
3
// and does not cause a loss of the resource.
4
//
5
pub fun alwaysUse(resource: @SomeResource, destroyResource: Bool) {
6
if destroyResource {
7
destroy resource
8
} else {
9
use(resource: <-resource)
10
}
11
// At the end of the function the resource parameter was definitely used:
12
// It was either destroyed or moved in the call of function `use`.
13
}
1
// Declare a function which has a resource parameter.
2
// This function is invalid, because it does not always use the resource parameter,
3
// which would cause a loss of the resource.
4
//
5
pub fun returnBeforeDestroy(move: Bool) {
6
let res <- create SomeResource(value: 1)
7
if move {
8
use(resource: <-res)
9
return
10
} else {
11
// Invalid: When this function returns here, the resource variable
12
// `res` was not used, but must be.
13
return
14
}
15
// Invalid: the resource variable `res` was potentially moved in the
16
// previous if-statement, and both branches definitely return,
17
// so this statement is unreachable.
18
destroy res
19
}

Resource Variables

Resource variables cannot be assigned to, as that would lead to the loss of the variable's current resource value.

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

1
pub resource R {}
2
3
var x <- create R()
4
var y <- create R()
5
6
// Invalid: Cannot assign to resource variable `x`,
7
// as its current resource would be lost
8
//
9
x <- y
10
11
// Instead, use a swap statement.
12
//
13
var replacement <- create R()
14
x <-> replacement
15
// `x` is the new resource.
16
// `replacement` is the old resource.
17
18
// Or use the shift statement (`<- target <-`)
19
// This statement moves the resource out of `x` and into `oldX`,
20
// and at the same time assigns `x` with the new value on the right-hand side.
21
let oldX <- x <- create R()
22
// oldX still needs to be explicitly handled after this statement
23
destroy oldX

Resource Destructors

Resource may have a destructor, which is executed when the resource is destroyed. Destructors have no parameters and no return value and are declared using the destroy name. A resource may have only one destructor.

1
var destructorCalled = false
2
3
pub resource Resource {
4
5
// Declare a destructor for the resource, which is executed
6
// when the resource is destroyed.
7
//
8
destroy() {
9
destructorCalled = true
10
}
11
}
12
13
let res <- create Resource()
14
destroy res
15
// `destructorCalled` is `true`

Nested Resources

Fields in composite types behave differently when they have a resource type.

If a resource type has fields that have a resource type, it must declare a destructor, which must invalidate all resource fields, i.e. move or destroy them.

1
pub resource Child {
2
let name: String
3
4
init(name: String)
5
self.name = name
6
}
7
}
8
9
// Declare a resource with a resource field named `child`.
10
// The resource *must* declare a destructor
11
// and the destructor *must* invalidate the resource field.
12
//
13
pub resource Parent {
14
let name: String
15
var child: @Child
16
17
init(name: String, child: @Child) {
18
self.name = name
19
self.child <- child
20
}
21
22
// Declare a destructor which invalidates the resource field
23
// `child` by destroying it.
24
//
25
destroy() {
26
destroy self.child
27
}
28
}

Accessing a field or calling function on a resource field is valid, however moving a resource out of a variable resource field is not allowed. Instead, use a swap statement to replace the resource with another resource.

1
let child <- create Child(name: "Child 1")
2
let parent <- create Parent(name: "Parent", child: <-child)
3
4
child.name // is "Child 1"
5
parent.child.name // is "Child 1"
6
7
// Invalid: Cannot move resource out of variable resource field.
8
let childAgain <- parent.child
9
10
// Instead, use a swap statement.
11
//
12
var otherChild <- create Child(name: "Child 2")
13
parent.child <-> otherChild
14
// `parent.child` is the second child, Child 2.
15
// `otherChild` is the first child, Child 1.

Resources in Closures

Resources can not be captured in closures, as that could potentially result in duplications.

1
resource R {}
2
3
// Invalid: Declare a function which returns a closure which refers to
4
// the resource parameter `resource`. Each call to the returned function
5
// would return the resource, which should not be possible.
6
//
7
fun makeCloner(resource: @R): ((): @R) {
8
return fun (): @R {
9
return <-resource
10
}
11
}
12
13
let test = makeCloner(resource: <-create R())

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.

1
resource R {}
2
3
// Declare a constant for an array of resources.
4
// Create two resources and move them into the array.
5
// `resources` has type `@[R]`
6
//
7
let resources <- [
8
<-create R(),
9
<-create R()
10
]
11
12
// Invalid: Reading an element from a resource array is not allowed.
13
//
14
let firstResource <- resources[0]
15
16
// Invalid: Setting an element in a resource array is not allowed,
17
// as it would result in the loss of the current value.
18
//
19
resources[0] <- create R()
20
21
// Instead, when attempting to either read an element or update an element
22
// in a resource array, use a swap statement with a variable to replace
23
// the accessed element.
24
//
25
var res <- create R()
26
resources[0] <-> res
27
// `resources[0]` now contains the new resource.
28
// `res` now contains the old resource.
29
30
// Use the shift statement to move the new resource into
31
// the array at the same time that the old resource is being moved out
32
let oldRes <- resources[0] <- create R()
33
// The old object still needs to be handled
34
destroy oldRes

The same applies to dictionaries.

1
// Declare a constant for a dictionary of resources.
2
// Create two resources and move them into the dictionary.
3
// `resources` has type `@{String: R}`
4
//
5
let resources <- {
6
"r1": <-create R(),
7
"r2": <-create R()
8
}
9
10
// Invalid: Reading an element from a resource dictionary is not allowed.
11
// It's not obvious that an access like this would have to remove
12
// the key from the dictionary.
13
//
14
let firstResource <- resources["r1"]
15
16
// Instead, make the removal explicit by using the `remove` function.
17
let firstResource <- resources.remove(key: "r1")
18
19
// Invalid: Setting an element in a resource dictionary is not allowed,
20
// as it would result in the loss of the current value.
21
//
22
resources["r1"] <- create R()
23
24
// Instead, when attempting to either read an element or update an element
25
// in a resource dictionary, use a swap statement with a variable to replace
26
// the accessed element.
27
//
28
// The result of a dictionary read is optional, as the given key might not
29
// exist in the dictionary.
30
// The types on both sides of the swap operator must be the same,
31
// so also declare the variable as an optional.
32
//
33
var res: @R? <- create R()
34
resources["r1"] <-> res
35
// `resources["r1"]` now contains the new resource.
36
// `res` now contains the old resource.
37
38
// Use the shift statement to move the new resource into
39
// the dictionary at the same time that the old resource is being moved out
40
let oldRes <- resources["r2"] <- create R()
41
// The old object still needs to be handled
42
destroy oldRes

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

1
let resource <- create R()
2
3
// Invalid: The resource variable `resource` can only be moved into the array once.
4
//
5
let resources <- [
6
<-resource,
7
<-resource
8
]
1
let resource <- create R()
2
3
// Invalid: The resource variable `resource` can only be moved into the dictionary once.
4
let resources <- {
5
"res1": <-resource,
6
"res2": <-resource
7
}

Resource arrays and dictionaries can be destroyed.

1
let resources <- [
2
<-create R(),
3
<-create R()
4
]
5
destroy resources
1
let resources <- {
2
"r1": <-create R(),
3
"r2": <-create R()
4
}
5
destroy resources

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.

1
let resources <- [<-create R()]
2
// `resources.length` is `1`
3
4
resources.append(<-create R())
5
// `resources.length` is `2`
6
7
let first <- resource.remove(at: 0)
8
// `resources.length` is `1`
9
destroy first
10
11
resources.insert(at: 0, <-create R())
12
// `resources.length` is `2`
13
14
// Invalid: The statement ignores the result of the call to `remove`,
15
// which would result in a loss.
16
resource.remove(at: 0)
17
18
destroy resources

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.

1
let resources <- {"r1": <-create R()}
2
// `resources.length` is `1`
3
4
let first <- resource.remove(key: "r1")
5
// `resources.length` is `0`
6
destroy first
7
8
let old <- resources.insert(key: "r1", <-create R())
9
// `old` is nil, as there was no value for the key "r1"
10
// `resources.length` is `1`
11
12
let old2 <- resources.insert(key: "r1", <-create R())
13
// `old2` is the old value for the key "r1"
14
// `resources.length` is `1`
15
16
destroy old
17
destroy old2
18
destroy resources

Resource Identifier

Resources have an implicit unique identifier associated with them, implemented by a predeclared public field let uuid: UInt64 on each resource.

This identifier will be automatically set when the resource is created, before the resource's initializer is called (i.e. the identifier can be used in the initializer), and will be unique even after the resource is destroyed, i.e. no two resources will ever have the same identifier.

1
// Declare a resource without any fields.
2
resource R {}
3
4
// Create two resources
5
let r1 <- create R()
6
let r2 <- create R()
7
8
// Get each resource's unique identifier
9
let id1 = r1.uuid
10
let id2 = r2.uuid
11
12
// Destroy the first resource
13
destroy r1
14
15
// Create a third resource
16
let r3 <- create R()
17
18
let id3 = r3.uuid
19
20
id1 != id2 // true
21
id2 != id3 // true
22
id3 != id1 // true

The details of how the identifiers are generated is an implementation detail.

Do not rely on or assume any particular behaviour in Cadence programs.

Resource Owner

Resources have the implicit field let owner: PublicAccount?. If the resource is currently stored in an account, then the field contains the publicly accessible portion of the account. Otherwise the field is nil.

The field's value changes when the resource is moved from outside account storage into account storage, when it is moved from the storage of one account to the storage of another account, and when it is moved out of account storage.

Unbound References / Nulls

There is no support for null.

Inheritance and Abstract Types

There is no support for inheritance. Inheritance is a feature common in other programming languages, that allows including the fields and functions of one type in another type.

Instead, follow the "composition over inheritance" principle, the idea of composing functionality from multiple individual parts, rather than building an inheritance tree.

Furthermore, there is also no support for abstract types. An abstract type is a feature common in other programming languages, that prevents creating values of the type and only allows the creation of values of a subtype. In addition, abstract types may declare functions, but omit the implementation of them and instead require subtypes to implement them.

Instead, consider using interfaces.