DocsLanguage Guide
Generics
Generic functions and types, constraints and where clauses, specialisation and variance.
Generic code is written once and works with many types. The array family, Optional, Dictionary and the sequence algorithms are all generic: an Int[>..] and a String[>..] are the same code applied to different element types. This chapter shows how to write generic functions and types of your own, how to constrain them, and how Sable compiles them.
Sable's generics look like Swift's and C#'s. Like Rust's and C++'s, they are compiled separately for each set of types they're used with — monomorphised — so generic code runs as fast as code written for one type. When you'd rather have one shared copy, you can ask for it.
The problem generics solve#
Here's a function that returns the larger of two integers:
fn larger(_ a: Int, _ b: Int) -> Int { return a >= b ? a : b}The same logic works for F64, String, or any type whose values can be ordered, but this version only takes Int. Writing largerF64, largerString and so on would repeat the same body for each. A generic function writes it once.
Generic functions#
A generic function declares type parameters in angle brackets after its name. Each stands for a type that the caller chooses:
fn larger<T: Comparable>(_ a: T, _ b: T) -> T { return a >= b ? a : b}print(larger(3, 7))// prints 7print(larger("pear", "apple"))// prints pearT is a placeholder: inside the function it's a type like any other, used for the parameters and the result. T: Comparable is a constraint, which says that T must conform to Comparable; without it, the body couldn't use >=, because not every type can be compared.
You don't write the type when you call the function: Sable infers it from the arguments. Here T is Int in the first call and String in the second. Both arguments must agree, so larger(3, "apple") is an error.
A function may have several type parameters, and they need no constraints when the body only moves values around:
fn swapped<A, B>(_ pair: (A, B)) -> (B, A) { return (pair.1, pair.0)}let flipped = swapped((1, "one")) // ("one", 1)Name type parameters for what they mean — Element, Key, Value — or with a single capital letter like T when there's no better name.
Generic types#
Structs, classes and unions can be generic too. Here's a stack of any element type:
struct Stack<Element> { private var items: Element[>..] = [] init() { } mutating fn push(_ item: Element) { items.append(item) } mutating fn pop() -> Element? { if items.count == 0 { return none } return items.removeLast() } var top: Element? => items.count == 0 ? none : items[items.count - 1]}var pending = Stack<String>()pending.push("compile")pending.push("link")print(pending.pop() ?? "")// prints linkStack<String> is a type: the generic Stack with Element set to String. Where the type arguments can be inferred — from a record literal's fields, an initialiser's arguments, or the type the context wants — you may leave them out:
let numbers: Stack<Int> = Stack() // Element is Int, from the annotationThe standard library's unions are generic in the same way. Outcome<T, E> holds a success or a failure:
union Outcome<T, E> { Ok(T) Err(E) fn map<U>(_ f: (T) -> U) -> Outcome<U, E> { return match self { case .Ok(let v) => .Ok(f(v)) case .Err(let e) => .Err(e) } }}map is a generic method of a generic type: it has a type parameter U of its own as well as the type's T and E. A recursive case of a generic union, such as a tree's Node(value: T, left: Tree<T>, right: Tree<T>), is boxed automatically. A type's initialisers may be generic too.
Type constraints#
A constraint limits what a type parameter may be, and in return lets the body use what the constraint promises. It's written after the parameter's name with a colon:
struct Cache<Key: Hashable, Value> { private var items: [Key: Value] = [:] fn get(_ key: Key) -> Value? => items[key] mutating fn put(_ key: Key, _ value: Value) { items[key] = value }}A dictionary's key must be Hashable, so Cache passes that constraint on. These are the kinds of constraint:
| Constraint | Means |
|---|---|
T: P |
T conforms to protocol P |
T: P & Q |
T conforms to both |
T: Widget |
T is the class Widget or a subclass of it |
where T.Element == U |
two types are the same |
T: Sendable |
values of T may cross between tasks |
T: ~Copyable |
T may be a move-only type (lifts the implicit Copyable) |
N: Int |
N is a number, not a type (see Value parameters) |
Calling a generic function with a type that doesn't meet its constraints is an error that names the constraint (S3023).
Copyable and ~Copyable#
Every type parameter is implicitly Copyable: generic code may copy its values, as it may an Int. A move-only type — a @noncopy struct, such as a lock or a file handle — can't be copied, so it doesn't fit a plain T. To write a container that can hold one, write ~Copyable, which removes the implicit constraint:
struct Box<T: ~Copyable> { var value: T}fn keep<T: ~Copyable>(_ x: consuming T) -> Box<T> { return Box(value: x)}The body of such code may only move values of T, never copy them. ~Copyable may also be written in a where clause, where T: ~Copyable, but only as a type parameter's constraint (S3203). Move-only types are covered in Memory and Ownership.
Where clauses#
Constraints that involve more than one parameter, or a parameter's associated types, go in a where clause before the body:
fn allEqual<A: Sequence, B: Sequence>(_ a: A, _ b: B) -> Bool where A.Element == B.Element, A.Element: Equatable, A.Failure == Never, B.Failure == Never { var other = b.makeIterator() for x in a { guard let y = other.next() else { return false } if x != y { return false } } return other.next() == none}A.Element == B.Element is a same-type constraint: the two sequences have the same element type, so their elements can be compared. A where clause may hold any constraint, including the simple T: P kind, which some prefer there when a signature is long:
fn zip<A, B, S1, S2>(_ a: S1, _ b: S2) -> some Sequence<(A, B)> where S1: Sequence<A>, S2: Sequence<B>, A: Sendable { }S1: Sequence<A> uses a protocol's primary associated type (from Protocols): S1 is a sequence whose Element is A.
some in parameter position#
A parameter of type some P is shorthand for a type parameter constrained to P that only that parameter uses. These two declarations mean the same:
fn describe(_ shape: some Shape) -> String { return shape.name }fn describe<S: Shape>(_ shape: S) -> String { return shape.name }Use some when the type is needed only once; name the parameter when two parameters must share a type, or the result must be that type.
Constraints on a method: where Self#
A method may have a where clause of its own, constraining the type it belongs to, or Self inside a protocol extension. The condition is checked at each call, and holds inside the method's body:
protocol Services { }extension Services { fn resolve<T>(_ type: T.Type) -> T where Self: Provides<T> { return provide(type) }}Here resolve may be called only for a T the conforming type provides (Provides is the generic protocol from Protocols), and inside it provide is known to exist.
Inferring type arguments#
Sable infers type arguments from the arguments of a call and, when they don't settle them, from the type the context expects. Inference works in both directions:
fn zero<T: AdditiveArithmetic>() -> T { return T.zero }let n: F64 = zero() // T is F64, from the annotationlet v: SIMD<F32, 4> = SIMD(repeating: 1) // the type's arguments, likewiseA metatype argument also settles a type parameter: fn make<T: Defaulted>(_ type: T.Type) -> T called as make(Settings.self) makes a Settings (Casting, Metatypes and Reflection).
The operands of an operator are each other's context, so zero() + x works with x: F64: the left operand takes its type from the right. Function parameter types, return types, stored properties and public signatures are never inferred: they are always written, which keeps module interfaces stable and error messages local.
A default argument is worked out at each call that leaves it off, so its type parameters are what that call gives them: fn count<E>(_ q: Queue<E> = Queue<E>()), called on F64s, makes a Queue<F64>.
Generic aliases#
An alias may have type parameters. It can give a long generic type a shorter name, fix some of its arguments (partial application), or add a parameter it doesn't use, to tell otherwise identical types apart:
alias Pairs<T> = (T, T)[>..]public alias Result<T> = Outcome<T, AppError> // E fixed to AppErroralias Id<T> = U64 // a phantom parameterCalled where an initialiser is expected, a generic alias infers its parameters as a generic type does. With alias GzipReader<R: Reader> = DecompressingReader<GzipDecoder, R>, GzipReader(file) for a file: FileHandle is a DecompressingReader<GzipDecoder, FileHandle>.
Conditional conformance#
A generic type may conform to a protocol only when its type arguments do. The conformance is declared in an extension with a where clause:
extension Stack: Equatable where Element: Equatable { operator == (lhs: Stack<Element>, rhs: Stack<Element>) -> Bool { return lhs.items == rhs.items }}A Stack<Int> is now Equatable, and a Stack<any Shape> isn't. The standard library uses this everywhere: an optional is Equatable when what it holds is, and every kind of array is Equatable, Hashable and Comparable when its element is:
extension<T: Equatable> T[:]: Equatable { }extension Optional<T>: Serializable where T: Serializable { }The first form, for arrays, is explained in Extensions.
Value parameters#
A type parameter constrained to an integer type, N: Int, stands for a number rather than a type. It's given one in the type, Ring<Int, 4>, or inferred from such a type, reads as that number in the body, and can size an inline array:
struct Ring<T, N: Int> where N > 0 { var slots: T[N]}fn capacity<T, N: Int>(_ ring: Ring<T, N>) -> Int { return N}let ring = Ring<Int, 2> { slots: [1, 2] }print(capacity(ring))// prints 2Each instance is a type of its own: Ring<Int, 2> and Ring<Int, 3> are different types. A where clause over value parameters — whole numbers, true, false and operators — is checked for each instance, and a false one is an error (S3421), so Ring<Int, 0> doesn't compile.
A value parameter may also be given a named constant, SIMD<F32, lanes>, if the compiler can work its value out as it reads the type: literals, other such constants, and integer operators on them. A constant computed by calling a function is evaluated too late for that (S3420).
How generics are compiled#
Monomorphisation#
By default, each distinct set of type arguments gets its own compiled copy of the generic code. larger<Int> and larger<String> are two functions, each as fast as one written by hand for its type: calls through the constraint are direct, they can be inlined, and a Stack<Vec3> stores its Vec3s inline with no boxing.
The cost is code size and compile time. The next two sections are the ways to trade some speed for less code.
One copy with any#
When you want one copy of the code for every type, use an existential instead of a type parameter: a function taking any Shape is compiled once and calls Shape's requirements through a table. The difference from some Shape is the trade-off between the two.
@polymorphic#
@polymorphic keeps a generic signature but compiles the function once, as if each type parameter were any of its constraints. A value of a type parameter is passed in a box with its type's witness table, and a result of a type parameter is taken back out of its box as the type the caller gave. It's for generic code that is cold, or deep in a large generic tree, where the copies cost more than the speed is worth:
@polymorphicfn describe<S: Shape>(_ s: S, times: Int) -> String { var total = 0.0 for _ in 0..<times { total += s.area() } return "\(s.name) \(total)"}Because every call shares one body, some generic signatures can't be compiled this way (S3512):
- each of the function's type parameters must be constrained to protocols only, with no associated types and no requirements that mention
Self; - each parameter, and the result, must be exactly a type parameter or not mention one at all — not
T?orT[]; - no parameter of a type parameter may be
inout.
Taken as a value rather than called, a @polymorphic function is still compiled for its types.
@inlinable#
A library's generic function is normally compiled once into the library, and only small ones are specialised in the programs that use it. @inlinable puts the function's body in the library's interface, so that an optimised program built against the library specialises it for the types it uses, whatever its size.
Variance#
Generic types are invariant: a Stack<Dog> is not a Stack<Animal>, even if Dog is a subclass of Animal. That's essential for a mutable container — if a Stack<Dog> could be used as a Stack<Animal>, someone could push a Cat onto it. Arrays are invariant for the same reason.
A generic protocol may declare its parameters variant, which is safe when the parameter is used in only one direction:
protocol Producer<out T> { fn next() -> T?}protocol Consumer<in T> { fn accept(_ value: T)}let p: any Producer<Animal> = DogProducer() // allowed: T is 'out'An out parameter is covariant: it may appear only in results, so a producer of dogs is a producer of animals. An in parameter is contravariant: it may appear only in parameters, so a consumer of animals can take dogs. Sable checks the declaration: an out parameter in an input position, an in parameter in an output position, or either one somewhere both read and written (a { get set } property, or an array result) is an error (S3047). A closure parameter flips the direction: fn register(_ callback: (T) -> Void) is an output use of T.
Variance is declared on the protocol, never at the use site.
Generic types as values#
A generic type's name without arguments, Stack.self, is a value too: the generic type itself, which can be given type arguments at run time to make a type. That, and how T.self works inside generic code, are covered in Casting, Metatypes and Reflection.