Contents Open

DocsLanguage Guide

Structures and Classes

Values and objects: record literals, memberwise initialisers, identity and inheritance.

Structures and classes are the building blocks you use to model your program's data. You declare the fields, properties and methods each one has with the same syntax, and you use both to group related values under one name. They differ in one deep way: a structure is a value, copied whenever you assign it, and a class is an object, an instance on the heap with an identity of its own that many references can share.

This chapter compares the two, shows how to declare and create them, and covers what only classes can do: identity, inheritance and overriding. The chapters that follow fill in the members: Properties, Methods, Subscripts and Operators and Initialization and Deinitialization.

Comparing Structures and Classes#

Structures and classes in Sable have a lot in common. Both can:

  • store values in fields, and define computed properties;
  • define methods, subscripts and operators;
  • define initialisers to set up their starting state;
  • nest other types inside them;
  • conform to protocols, and be extended with extensions;
  • be generic, as covered in Generics.

Classes can also do things structures can't:

  • Identity. Two references can point at the same object, and you can ask whether they do with ===.
  • Inheritance. One class can build on another, and override its members.
  • Deinitialisers. A class's deinit runs when the last reference to an object goes away.
  • Weak and unowned references to an object, which don't keep it alive.

These extra abilities have a cost. A class instance lives on the heap with a 16-byte header and a reference count that Sable maintains for you (automatic reference counting, or ARC). A struct has no header, no count and no identity: it is exactly its fields' bytes, stored wherever it is, inline in another struct, in an array or in a local variable. Sable calls these the memory tiers: structs are Tier 0, the default for data; classes are Tier 2, the default for things with identity; and between them sit regions, Tier 1, for allocating many short-lived values at once. Memory and Ownership explains all three.

Tip

Reach for a struct by default. Use a class when the thing you're modelling has an identity: a document that several windows show, a connection, a node in a graph that others point at.

Declaring Structures and Classes#

You introduce a structure with struct and a class with class, and put the definition inside braces:

Sable
struct Resolution {    var width: Int    var height: Int}class VideoMode {    var resolution = Resolution { width: 0, height: 0 }    var interlaced = false    var frameRate = 0.0    var name: String? = none}

Each var declares a stored field, a value kept as part of every instance. Resolution has two, both Int. VideoMode has four, each with an initial value, so the type of each is inferred from it. Type names are written in UpperCamelCase and members in lowerCamelCase.

Note

An optional field isn't given none for you. Write = none when you want it to start empty; without it, the field must be set by an initialiser like any other.

Immutable fields without a keyword#

Inside a type body, a field may be written as just name: Type. That declares an immutable stored field, exactly as let name: Type would. You write var only when a field needs to change:

Sable
struct Vec3 {    x: F32    y: F32    z: F32}

This makes the common case, a small value type whose parts are fixed once it is made, as short as it can be. To change a Vec3 you make a new one.

One-line bodies#

Members on their own lines need no separator. When you put several on one line, separate them with , or ;:

Sable
struct Vec3 { x: F32, y: F32, z: F32 }struct Size { var width = 0.0; var height = 0.0 }

The same rule holds for the cases of enums and unions, which you'll meet in Enums and Unions: enum Direction { North, South, East, West }.

Creating Instances#

A structure can be created in two ways: with a record literal or by calling an initialiser.

Record literals#

A record literal names the type and gives each field a value, in braces:

Sable
let hd = Resolution { width: 1920, height: 1080 }print(hd.width)// prints 1920

Fields that have an initial value may be left out, and { } alone makes a value from every field's initial value. Every field written carries its value: there is no field shorthand, so Resolution { width, height } is not a way to write Resolution { width: width, height: height }. The reason is the brace. After a type name, { } or { name: … is a record literal, and anything else is a trailing closure, as described in Closures. Point { x } would be indistinguishable from a closure that returns x, so a field always says what it is set to.

Record literals are for structures. A class is made by calling one of its initialisers.

Memberwise initialisers#

Unless a structure declares an initialiser of its own, Sable generates a memberwise initialiser for it: an init with one labelled parameter per stored field, in the order they're declared. A field with an initial value becomes a parameter you may leave out:

Sable
var size = Size(width: 2.0)size.height = 3.0print("\(size.width) × \(size.height)")// prints 2.0 × 3.0let empty = Size()

Once you write an init yourself, the memberwise one is no longer generated. Initialization covers writing initialisers, for structs and for classes.

A class with nothing to set#

A class doesn't get a memberwise initialiser. But a class that declares no init, and whose stored fields all have initial values, is made with an implicit init():

Sable
let tenEighty = VideoMode()tenEighty.resolution = hdtenEighty.frameRate = 25.0

If any field of such a class lacks an initial value, the class has no way to be made until you write an initialiser (S3020).

Accessing Fields#

You read and write a field with dot syntax, and drill into nested values the same way:

Sable
print("The width of tenEighty is \(tenEighty.resolution.width)")// prints The width of tenEighty is 1920

Printing or interpolating a struct describes it field by field:

Sable
print(hd)// prints Resolution(width: 1920, height: 1080)

Record Destructuring#

You can take a struct apart by field name. A let (or var) whose pattern is braces binds each named field to a constant of the same name:

Sable
struct Person {    var name: String    var age: Int}let person = Person(name: "Ada", age: 36)let { name, age } = personprint("\(name) is \(age)")// prints Ada is 36

Give a field a different local name with field: newName, and leave out the fields you don't need:

Sable
let { name: who } = personprint(who)// prints Ada

Naming a field the type doesn't have is an error. Here, unlike in a record literal, the shorthand is allowed: the let in front means there is no closure it could be confused with. Destructuring in match arms, case Point { x: 0, y: let y }, is covered in Pattern Matching.

Structures Are Value Types#

A value type is one whose value is copied when it's assigned to a variable or constant, or passed to a function. Every struct is a value type, and so are all of Sable's basic types, its arrays, strings and dictionaries.

Sable
let hd = Resolution { width: 1920, height: 1080 }var cinema = hdcinema.width = 2048print("cinema is \(cinema.width) pixels wide")// prints cinema is 2048 pixels wideprint("hd is still \(hd.width) pixels wide")// prints hd is still 1920 pixels wide

cinema was given a copy of hd. Changing the copy didn't touch the original: they are two separate values that happened to start out equal.

Whether you may change a struct depends on how you hold it. A struct in a let can't be changed at all, not even its var fields; one in a var can. Methods that change a struct must be marked mutating, covered in Methods.

Note

Copies are cheap. A struct is just its bytes, and Sable's arrays and strings share their storage until one copy is changed (copy-on-write). A struct that must never be copied, a file handle or a lock, can be declared @noncopy and is then moved instead: see Memory and Ownership.

Classes Are Reference Types#

A class instance isn't copied when it's assigned or passed. What is copied is a reference to the same object:

Sable
let alsoTenEighty = tenEightyalsoTenEighty.frameRate = 30.0print(tenEighty.frameRate)// prints 30.0

tenEighty and alsoTenEighty refer to one VideoMode. Notice that both are lets, yet the frame rate changed: a let holding a class fixes which object it refers to, not the object's fields.

Identity operators#

Because several constants and variables can refer to one object, it is useful to ask whether two of them do. Sable has two identity operators:

  • ===, identical to: both refer to the same instance;
  • !==, not identical to.
Sable
if tenEighty === alsoTenEighty {    print("the same VideoMode")}// prints the same VideoModeprint(tenEighty !== VideoMode())// prints true

"Identical" isn't "equal". === asks whether two references are one object; == asks whether two values are equal, in whatever sense the type defines, as shown in Operator Overloading. Identity is only defined for classes: === between two structs is an error (S3009), since a value has no identity to compare.

Inheritance#

A class may inherit from one other class, its superclass, and is then its subclass. It gets every field and method of the superclass, and may add its own and replace some of the superclass's. Sable has single inheritance of classes, like Swift and C#; a class may conform to any number of protocols besides.

You write the superclass after a colon:

Sable
open class Vehicle {    var currentSpeed = 0.0    var description: String => "travelling at \(currentSpeed) km/h"    fn makeNoise() { }}class Bicycle: Vehicle {    var hasBasket = false}let bicycle = Bicycle()bicycle.hasBasket = truebicycle.currentSpeed = 15.0print("Bicycle: \(bicycle.description)")// prints Bicycle: travelling at 15.0 km/h

A subclass can be subclassed in turn:

Sable
class Tandem: Bicycle {    var passengers = 0}

The same colon lists the protocols a class conforms to: class Document: Serializable, Equatable.

Overriding#

A subclass replaces a member it inherits by declaring it again with override. The keyword is mandatory: a method that happens to match a superclass's without it is an error (S3042), and so is an override of something no superclass declares (S3043). That way neither an accidental override nor a misspelt intended one goes unnoticed.

Sable
class Train: Vehicle {    override fn makeNoise() {        print("Choo Choo")    }}let train: Vehicle = Train()train.makeNoise()// prints Choo Choo

The call goes to Train's method even through a Vehicle. Properties are overridden the same way:

Sable
class Car: Vehicle {    var gear = 1    override var description: String => super.description + " in gear \(gear)"}

An override must keep the signature it replaces: the same parameter and result types, and the same thrown error type (S3065). A property that can be written must stay writable in the override.

Accessing the superclass with super#

Inside an override, super reaches the superclass's version of a member: super.makeNoise(), super.description. In an initialiser, super.init(…) runs the superclass's initialiser, as covered in Class Initialisation.

Who may subclass and override#

Sable is conservative about dynamic dispatch, because a call the compiler can resolve statically can be inlined and optimised. Members are non-virtual unless something makes them otherwise:

  • Within the module that declares a class, you may subclass it and override any of its members that aren't final. The compiler sees every override, so a method nobody overrides is called directly.
  • From another module, you may subclass only an open class, and override only open (or abstract) members. Without open, the compiler is free to devirtualise calls across the module boundary.

Three more modifiers close or shape a hierarchy:

Modifier Effect
final class The class can't be subclassed at all (S3044).
final fn, final var That one member can't be overridden (S3044).
sealed class The class may not be subclassed any further, even in its own module.
abstract class The class can't be instantiated (S3045); only subclasses can.
abstract fn A method with no body, which every concrete subclass must override.
Sable
abstract class Shape {    abstract fn area() -> F64    fn report() -> String { return "area \(area())" }}final class Square: Shape {    var side: F64    init(_ side: F64) { self.side = side }    override fn area() -> F64 { return side * side }}let shape: Shape = Square(3.0)print(shape.report())// prints area 9.0

The rules for open, public and the other visibility levels are in Modules and Access Control.

Self in Expressions#

Inside a type, Self names the enclosing type. In an expression it is a shorter way to write the type's name: Self(x: 3) makes one, and Self.zero reads a static member.

Sable
struct Vec2 {    var x: F64, var y: F64    static let zero = Vec2(x: 0, y: 0)    fn flipped() -> Self { return Self(x: y, y: x) }    fn isZero() -> Bool { return self.x == Self.zero.x && self.y == Self.zero.y }}

Lowercase self is the instance a method was called on; it's covered with methods in Methods, Subscripts and Operators.

Nested Types#

A struct, class, union or enum may declare other types inside its body. They're named from outside through the outer type:

Sable
struct BlackjackCard {    enum Suit { Spades, Hearts, Diamonds, Clubs }    let rank: Int    let suit: Suit}let card = BlackjackCard(rank: 1, suit: .Hearts)let trumps: BlackjackCard.Suit = .Clubsprint("\(card.suit) \(trumps)")// prints Hearts Clubs

Nesting keeps a helper type next to the one it serves, and out of the module's top-level names.

Explicit Protocol Implementation#

A type that conforms to two protocols may find both require a member of the same name. Sable lets you implement each one separately, C#-style, by writing the protocol's name before the member's:

Sable
protocol Drawable { fn render() -> String }protocol Printable { fn render() -> String }class Chart: Drawable, Printable {    fn Drawable.render() -> String { return "pixels" }    fn Printable.render() -> String { return "ink" }}let chart = Chart()let screen: any Drawable = chartlet paper: any Printable = chartprint("\(screen.render()) \(paper.render())")// prints pixels ink

Each one meets only its own protocol's requirement, and the type must conform to the protocol it names. Protocols, and any, are the subject of Protocols.

Weak and Unowned Fields#

A class field normally holds a strong reference, which keeps the object it refers to alive. Two objects that hold each other strongly are never released: ARC can't reclaim a cycle. To break one, mark one side weak or unowned:

Sable
class Owner {    var name: String    var pet: Pet? = none    init(name: String) { self.name = name }}class Pet {    weak var owner: Owner? = none     // doesn't keep the owner alive}

A weak field is always an optional var, and becomes none when its object goes away. An unowned field, unowned let parent: Node, is not optional and assumes the object outlives it; reading it after the object is gone traps. The compiler also warns about strong cycles it can see between your types. Memory and Ownership covers reference counting, cycles and both kinds of reference in full.

Actors#

There is a third kind of reference type: the actor. An actor is declared like a class, with actor in place of class, but it protects its state from concurrent access by running one call at a time. Code outside it must await its methods:

Sable
actor Counter {    private var value = 0    fn increment() { value += 1 }}let counter = Counter()await counter.increment()

They're covered with the rest of Sable's concurrency in Concurrency.

Sable

A systems language with value semantics, automatic reference counting, move-checked resources and compile-time checks on how memory is used, compiled ahead of time to native code through LLVM.

Sable is pre-1.0: the language, the standard library and the toolchain work end to end, but expect changes between versions.