Composite Type Declaration and Creation

Structures are declared using the struct keyword and resources are declared using the resource keyword. The keyword is followed by the name.

pub struct SomeStruct {
    // ...
}

pub resource SomeResource {
    // ...
}

Structures and resources are types.

Structures are created (instantiated) by calling the type like a function.

// instantiate a new struct object and assign it to a constant
let a = SomeStruct()

The constructor function may require parameters if the initializer of the composite type requires them.

Composite types can only be declared within contracts and not locally in functions. They can also not be nested.

Resource must be created (instantiated) by using the create keyword and calling the type like a function.

Resources can only be created in functions and types that are declared in the same contract in which the resource is declared.

// instantiate a new resource object and assign it to a constant
let b <- create SomeResource()

Composite Data Initializer Overloading

🚧 Status: Initializer overloading is not implemented yet.

Initializers support overloading. This allows for example providing default values for certain parameters.

// Declare a structure named `Token`, which has a constant field
// named `id` and a variable field named `balance`.
//
// The first initializer allows initializing both fields with a given value.
//
// A second initializer is provided for convenience to initialize the `id` field
// with a given value, and the `balance` field with the default value `0`.
//
pub struct Token {
    let id: Int
    var balance: Int

    init(id: Int, balance: Int) {
        self.id = id
        self.balance = balance
    }

    init(id: Int) {
        self.id = id
        self.balance = 0
    }
}

Last updated