Structs

A struct in Sway is a product type which is a data structure that allows grouping of various types under a name that can be referenced, unlike a tuple. The types contained in the struct are named and thus they can be referenced by their names as well.

Declaration

The following syntax demonstrates the declaration of a struct named Foo containing two fields - public field bar, a u64, and a private field baz, a bool.

struct Foo {
    pub bar: u64,
    baz: bool,
}

Public fields are accessible in all the modules in which the struct is accessible. Private fields are accessible only within the module in which the struct is declared.

Instantiation

To instantiate a struct the name of the struct must be used followed by {} where the fields from the declaration must be specified inside the brackets. Instantiation requires all fields to be initialized, both private and public.

fn hardcoded_instantiation() {
    // Instantiate the variable `foo` as `Foo`
    let mut foo = Foo {
        bar: 42,
        baz: false,
    };

    // Access and write to "baz"
    foo.baz = true;
}

fn variable_instantiation() {
    // Declare variables and pass them into `Foo`
    let number = 42;
    let boolean = false;

    let mut foo = Foo {
        bar: number,
        baz: boolean,
    };

    // Access and write to "baz"
    foo.baz = true;
}

fn shorthand_instantiation() {
    // Declare variables with the same names as the fields in `Foo`
    let bar = 42;
    let baz = false;

    // Instantiate `foo` as `Foo`
    let mut foo = Foo { bar, baz };

    // Access and write to "baz"
    foo.baz = true;
}

Structs with private fields can be instantiated only within the module in which the struct is declared.

Destructuring

The fields of a struct can be accessed through destructuring.

fn destructuring() {
    let foo = Foo {
        bar: 42,
        baz: false,
    };

    // bar and baz are now accessible as variables
    let Foo { bar, baz } = foo;

    if baz {
        let quix = bar * 2;
    }

    // You may use `..` to omit the remaining fields if the types match
    // The compiler will fill them in for you
    let Foo { bar, .. } = foo;
}

When destructuring structs with private fields outside of a module in which the struct is defined, the private fields must be omitted by using the ...