Style Guide

Programming languages have different ways of styling code i.e. how variables, functions, structures etc. are written.

The following snippets present the style for writing Sway.

CapitalCase

Structs, traits, and enums are CapitalCase which means each word has a capitalized first letter. The fields inside a struct should be snake_case and CapitalCase inside an enum.

struct MultiSignatureWallet {
    owner_count: u64,
}

trait MetaData {
    // code
}

enum DepositError {
    IncorrectAmount: (),
    IncorrectAsset: (),
}

snake_case

Modules, variables, and functions are snake_case which means that each word is lowercase and separated by an underscore.

Module name:

library;

Function and variable:

fn authorize_user(user: Identity) {
    let blacklist_user = false;
    // code
}

SCREAMING_SNAKE_CASE

Constants are SCREAMING_SNAKE_CASE which means that each word in capitalized and separated by an underscore.

const MAXIMUM_DEPOSIT = 10;

Type Annotations

When declaring a variable it is possible to annotate it with a type however the compiler can usually infer that information.

The general approach is to omit a type if the compiler does not throw an error however if it is deemed clearer by the developer to indicate the type then that is also encouraged.

fn execute() {
    // Avoid unless it's more helpful to annotate
    let executed: bool = false;

    // Generally encouraged
    let executed = false;
}

Field Initialization Shorthand

A struct has a shorthand notation for initializing its fields. The shorthand works by passing a variable into a struct with the exact same name and type.

The following struct has a field amount with type u64.

struct Structure {
    amount: u64,
}

Using the shorthand notation we can initialize the struct in the following way.

fn call(amount: u64) {
    let structure = Structure { amount };
}

The shorthand is encouraged because it is a cleaner alternative to the following.

fn action(value: u64) {
    let amount = value;
    let structure = Structure { amount: value };
    let structure = Structure { amount: amount };
}

Getters

Getters should not follow the pattern of get_XYZ() and instead should follow XYZ().

// Discouraged style
fn get_maximum_deposit() -> u64 {
    MAXIMUM_DEPOSIT
}

// Encouraged style
fn maximum_deposit() -> u64 {
    MAXIMUM_DEPOSIT
}