Skip to content

Types and values

A type’s shape, its inherent impl Type block and each impl Iface for Type are separate top-level declarations (spec §12 Implementations; tour: Interfaces & Dispatch). Put the impls of a type you declare right after it, where §2 places them, so a reader finds everything the type can do in one place:

struct Dog
    name: String
end

impl Dog
    fn rename(_d: Dog, new_name: String) -> Dog
        Dog{name: new_name}
    end
end

impl Speech for Dog
    fn speak(d: Dog) -> String
        "${d.name} says woof"
    end
end

A type is not a namespace for unrelated helpers. Choose a separate file when a name only groups functions; choose a type when the name should also be a value type (for example a zero-data capability that implements an interface, is stored in an application field, or is passed to a function). Related value types are ordinary sibling declarations (Days, Months).

For a generic type, put the constraints that always hold on the type declaration. Use a function-level or impl-level where for extra constraints that apply only there:

struct Span<T> where T: Comparable
    start: T
    stop:  T
end

impl Span<T>
    fn is_longer(a: Span<T>, b: Span<T>) -> Bool
        a.stop > b.stop
    end
end

An interface function with a type parameter of its own declares it in its header and constrains it with where:

interface Ranked<T>
    fn item(value: self) -> T
    fn prefer<K>(value: self, lhs: K, rhs: K) -> Bool where K: Comparable
end

A conformance with nothing to implement (a marker interface, or one with defaults only) is the one-line impl Iface for Type end.

14. Write one derive declaration per interface

Section titled “14. Write one derive declaration per interface”

Write one derive Iface for Type declaration per interface (spec §12 Derive; tour: Interfaces & Dispatch), where §2 places them:

type Off

derive Comparable for Off
derive Equatable for Off
derive Hashable for Off

struct Box<T>
    value: T
end

derive Display for Box<T> where T: Display

struct Account
    first_name: String
    age:        Int
end

derive ToJson for Account with ToJson.Options{rename_all: Json.Case.Camel}
derive FromJson for Account with FromJson.Options{rename_all: Json.Case.Camel}

Every type already has a Debug (spec §12 Display and Debug), so write derive Debug only on an opaque type, to show its structure in place of <opaque T>.

15. List an enum’s variants with derive Variants

Section titled “15. List an enum’s variants with derive Variants”

When code needs every variant of an enum, derive Variants (spec §12 Derivable interfaces; tour: Interfaces & Dispatch) and call variants(), rather than writing the list out. The list follows the declaration order, so a new variant joins it and the order lives in one place:

pub enum Nucleotide
    A
    C
    G
    T
end

derive Equatable for Nucleotide
derive Hashable for Nucleotide
derive Variants for Nucleotide

fn no_counts() -> Map<Nucleotide, Int>
    Nucleotide.variants() |> Iter.map(&(&1, 0)) |> Iter.to_map()
end

not {Nucleotide.A => 0, .C => 0, .G => 0, .T => 0}, which a fifth variant would leave behind.

Don’t compute a variant’s value from its position in that list. A value the problem states for each variant is a case with an arm per variant:

fn code(color: Color) -> Int
    case color
        .Black -> 0
        .Brown -> 1
        .Red   -> 2
    end
end

not Color.variants() |> Iter.find_index(&(&1 == color)), a search whose None the reader has to prove cannot happen, and whose results change when someone reorders the enum.

16. Leave out a literal’s type name where the context names it

Section titled “16. Leave out a literal’s type name where the context names it”

A variant leaves out its enum with a dot where the position names the enum: Shape.Circle{radius:} is .Circle{radius:}. A struct leaves out its name the same way: Point{x: 0} is {x: 0}, which builds the struct its position expects (spec §4 Target-typed construction; tour: Structs, Enums & Distinct Types). So where an annotation, a parameter, a field or a return type already names the struct, write {...} rather than Point{...}:

ada = Person{name: "Ada", address: {street: "1 Main", city: "Bath"}}

fn origin() -> Point
    {x: 0, y: 0}
end

Write the type name anyway when a reader cannot see the expected type from the literal’s own line: an argument to a function defined far away, an element deep inside a nested call, or a literal whose struct shares field names with another struct the reader might expect. Address{...} at the top of an expression also says what is being built before the fields do, so keep it on an unannotated binding (home = Address{...}), where {...} would make an anonymous struct instead.

The same holds for a variant. Where the expected type already names its enum (a return type, a parameter, a case subject, the list’s first element, a constructor’s payload), write .Accounting, not CurrencySign.Accounting, and drop the enum’s import once nothing else names it:

fn sign(style: Style) -> CurrencySign
    case style
        .American -> .Accounting
        .Dutch    -> .Standard
    end
end

A struct pattern works the same way. Where the value being matched already has the struct’s type (a case subject, the right side of a binding, a typed parameter), write {...}, not Order{...}:

fn describe(order: Order) -> String
    case order
        {status: .Paid, total:} when total > 100 -> "big order"
        {status: .Paid}                          -> "paid"
        {status: .Refunded}                      -> "refunded"
    end
end

Keep the name where it chooses the type: arms that match different structs of an embeds enum or an interface value, or a parameter pattern with no annotation (fn advance(Position{x:, y:}, ...)), where the name is the parameter’s type.

A collection literal works the same way (spec §3 Literal forms). [...] is the list, vector or set its position expects, so where an annotation, a parameter, a field or a return type names the collection, write the bare brackets; write Vector[...] or Set[...] only where nothing names it, as on an unannotated binding:

struct Grid
    cells: Vector<Int>
    seen:  Set<Int>
end

fn empty_grid() -> Grid
    {cells: [0, 0, 0], seen: []}
end

fn main()
    pending = Set[1, 2]
    dbg Set.size(pending)
end

A list and a map need no name anywhere: [1, 2] and {"k" => 1} are a List and a Map where nothing expects another collection. Never write List[...] or Map{...}.

17. Use a tuple for a local pairing and a struct once it travels

Section titled “17. Use a tuple for a local pairing and a struct once it travels”

Use a tuple, (a, b), for a small, local pairing whose positions are obvious (spec §4 Tuples; tour: Structs, Enums & Distinct Types): a function returning two values, a map entry. Switch to an anonymous struct, {x: 1, y: 2} (or a struct), once a slot is updated, or read by position far from where the tuple was built. A named field reads better than .second, and an anonymous struct takes a spread update, which a tuple does not. Past four items, use a struct: .fifth makes the reader count, and a field name says what the item is.

fn divide(x: Int, y: Int) -> (Int, Int)
    (x / y, x % y)
end

fn step(point: {x: Int, y: Int}) -> {x: Int, y: Int}
    {..point, y: .. + 1}
end

To change part of a nested value inside an update (spec §4 Struct Updates), write the bare .. ({..user, address: {.., city: "NYC"}}; repeating the path as a base, {..user.address, city: "NYC"}, is a compile error). Write a literal without .. only when the field gets a whole new value. A new value computed from the old one reads it as .. too: {..user, visits: .. + 1} and address: {.., street: rename(..)}, not rename(user.address.street), which repeats the path the field already names.

18. Read a distinct’s value by destructuring

Section titled “18. Read a distinct’s value by destructuring”

A distinct is read with the pattern that mirrors its construction (spec §10 Distinct Type Destructuring; tour: Structs, Enums & Distinct Types): Balance(n) = balance, a case arm, or a parameter (fn cents(Balance(n)) -> Int). The pattern names the distinct, so changing type Balance Int to type Balance Decimal leaves each one correct and only retypes n.

When other code reads the value in many places, give the type an accessor in its own file and call that:

type Balance Int

impl Balance
    pub fn cents(Balance(n)) -> Int
        n
    end
end

An opaque distinct needs one, since code outside its file cannot destructure it.

19. Use typealias only to shorten a long anonymous shape

Section titled “19. Use typealias only to shorten a long anonymous shape”

A typealias is another spelling of its target, with no identity of its own (spec §4 Type Aliases; tour: Structs, Enums & Distinct Types). Use one to shorten a long anonymous shape that signatures would otherwise repeat: an anonymous struct, a function type, a long tuple.

typealias Rule (String) -> Maybe<String>
typealias Span {start: Int, stop: Int, line: Int}

When the thing deserves a name, a domain concept that functions take and return, declare a struct or a type instead. A type is checked as its own type, and a struct names its fields. An alias of a named type (typealias UserList List<User>) only hides what the reader would see by writing List<User>.

20. Use a codepoint literal for codepoint work and a string for text

Section titled “20. Use a codepoint literal for codepoint work and a string for text”

A codepoint literal ('a') is a Codepoint, not a character of text (spec §3 Codepoint literals; tour: Scalars & Strings). Reach for it when the code works at the codepoint level: enumerating ASCII ('a'..='z'), scanning String.to_codepoints output, or matching delimiters in a case. Write 'a' rather than Int.to_codepoint(97)!: the literal is infallible and says which character it is.

fn is_delimiter(cp: Codepoint) -> Bool
    case cp
        ',' or ';' or '\t' -> True
        _                  -> False
    end
end

Keep text in strings, a one-character one included: String.starts_with(s, "#"), not a comparison against '#', and "é", which has no codepoint literal at all. Converting back and forth (Codepoint.to_string('a')) is a sign the value wanted to be a string.

21. Write a typed literal with backticks only when its text has backslashes

Section titled “21. Write a typed literal with backticks only when its text has backslashes”

A typed literal without ${...} slots is checked when the program compiles in any quote style (spec §18 A literal without slots is checked at compile time; tour: Typed Literals), so the quotes decide only how the text is read. Use backticks for text with backslashes, such as a regex, where a backtick body keeps each one as written. Use double quotes otherwise.

release = Date"2026-05-04"

digits = Regex`\d+`

Neither needs a ?: a good literal is the value itself, and a bad one is a compile error at the literal. To build a value from text known only when the program runs, call the type’s own function, such as Date.parse(text), or put the text in a slot.

22. Reach for the type that holds the value exactly: DateTime, and Decimal over Float

Section titled “22. Reach for the type that holds the value exactly: DateTime, and Decimal over Float”

std::calendar gives the bare name to the safe default (tour: Dates & Times): DateTime is zoned by an IANA time zone, DST-aware, and equal only to the same instant. NaiveDateTime carries its prefix as a warning. It is a wall-clock reading without a zone, not a moment in history.

// yes: a real moment, anchored
appointment = DateTime"2026-06-15T14:30:00-04:00[America/New_York]"

// only for wall time without a zone, which is rare
template_time = NaiveDateTime"2026-06-15T14:30:00"

If you find yourself writing a NaiveDateTime literal, check whether you want a DateTime with a zone. The naive type fits recurring schedule templates, form input before zone resolution, and naturally zone-less data such as birthdays. It does not fit “the meeting is at 2:30pm”: meetings happen in time zones.

A number with a fraction that people read, add up or compare, such as a price, a measurement, a score’s average or a percentage, is a Decimal. Its arithmetic is exact, so 0.1d + 0.2d is 0.3d; the same sum of Floats is 0.30000000000000004. Float is for science, graphics, statistics and other work where speed and range matter more than the last digit, and for values a Float-based library hands back. Money is Money (tour: Money).

// yes: read by people, added up
price = 19.99d

discount = 0.15d

total = price * (1d - discount)

// a measurement in a physics step, where Float's speed and range fit
velocity = velocity + acceleration * dt

23. Write bit operations with the operators

Section titled “23. Write bit operations with the operators”

Mask, combine and shift Ints with &&&, |||, ^^^, ~~~, <<< and >>> (spec §8 Bitwise operators; tour: Scalars & Strings), not with the Int.bitwise_* and Int.shift_* functions:

low = byte &&& 0x7F

value = value <<< 7 ||| low

not Int.bitwise_or(Int.shift_left(value, 7), Int.bitwise_and(byte, 0x7F)). The functions are for passing as values (Iter.reduce(flags, 0, Int.bitwise_or)). The shifts and &&& bind like *, so a shift count that is a sum or product takes parentheses: byte >>> (7 - i) &&& 1.

A Byte constant is an integer literal where a Byte is expected (b &&& 0x7F, bytes == [0x81, 0x00], spec §3 Byte literals), not Int.to_byte(0x7F)!.