Docs · Language

Types

This page lists every form a type can take, what each means, and the identity and conversion rules between them. Guides 02, Values and bindings, 03, Structs, enums, and tuples, and 09, Pointers and memory introduce them by example.

A type is a value: a known value whose type is type. Wherever this page says "type", any expression the compiler can evaluate to a type will do. That one rule gives generics, typeof, and values used as types; the known values reference has the details.

The type grammar at a glance

FormMeaning
i32, bool, char, and the other primitivesprimitive types
()the unit type, the empty tuple
struct { ... }a struct; nominal when declared with a name
enum { ... }an enum: a closed set of variants, each with or without a payload
interface { ... }an interface: a set of method signatures
(T, U)a tuple; structural
A | Ba structural union: a value of one of the listed types
?Tan optional, Optional(T)
E!Tan error union, Result(E, T)
!Tan error union whose error type is inferred, Result(_, T)
*mut T, *con Ta pointer to one T, writable or read-only
[N]Ta fixed array of N elements; N is part of the type
[*con]T, [*mut]Tan array pointer: a pointer and a run-time length
*c_ptr Ta C pointer: may be null, has arithmetic
fn(T, U) Ra function type
typethe type whose values are types
anythe type every value converts to
42, "go", 'a', truea singleton type, holding exactly that value
0..101a range type: an integer in the half-open interval
_an inference placeholder, worked out by the compiler

Primitive types

TypeSizeValues
i88 bits, signed-128 to 127
i1616 bits, signed-32768 to 32767
i3232 bits, signed-2147483648 to 2147483647
i6464 bits, signed-2^63 to 2^63 - 1
u88 bits, unsigned0 to 255
u1616 bits, unsigned0 to 65535
u3232 bits, unsigned0 to 4294967295
u6464 bits, unsigned0 to 2^64 - 1
iwpointer width, signed32 bits on wasm, 64 bits on the native Linux targets
uwpointer width, unsigned32 bits on wasm, 64 bits on the native Linux targets
f3232 bitsIEEE 754 single precision
f6464 bitsIEEE 754 double precision
bool1 bytetrue, false
char32 bitsone Unicode code point
()0 bytesthe single value ()
  • There is no int. An integer literal with nothing to decide its type is an i32; a float literal is an f64.
  • No number type converts to another on its own, not even to a wider one. Mixing two number types is a compile error until you write a conversion (expressions, casts).
  • char is not u8. One character of text can take up to four bytes of UTF-8.
  • There is no string primitive. A string literal is a [*con]u8, and the owned text type is String from @core (guide 10).

sizeof T is the type's storage size in bytes: sizeof u8 is 1 and sizeof i16 is 2. A struct lays out its fields at these sizes, each aligned to its own alignment, and sizeof S.x is the size of field x's type. Array elements are packed at their own size, so a [4]u8 is 4 bytes. A value always behaves as its declared type: a u8 holds 0 to 255.

Nominal identity, structural compatibility

A declared struct or enum is nominal: two declarations with the same fields are two different types. A struct value still converts to another struct type by shape: when it has every field of the target, with the same name and the same type, it copies into the target. Fields the target doesn't have are left behind, and the result is a new copy.

The conversion happens without being written wherever a value goes to a declared type: an argument, a return, a binding with a declared type, or a field in a struct literal. Target(value) writes it out:

Vyi
import { println } from "@fmt"

struct Order { id: i32, total: i32, note: [*con]u8 }
struct Receipt { id: i32, total: i32 }

fn totalOf(r: Receipt) i32 { return r.total }

fn main() !u8 {
    con order = Order{ id: 7, total: 4200, note: "door" }
    println(totalOf(order))     // prints 4200
    con r: Receipt = order
    println(r.id)               // prints 7
    println(Receipt(order).id)  // prints 7
    return Ok(0)
}

The source must have every field of the target. A field default fills a missing field in a literal, never in a conversion:

Vyi · does not compile
struct Server { host: i32, port: i32 = 80 }
struct Request { host: i32 }

fn main() !u8 {
    con req = Request{ host: 1 }
    con s: Server = req    // error: this value has type Request, but the binding is declared Server
    return Ok(0)
}

Unions also convert without being written: a member type into its union, and a union into a wider one (structural unions). Singleton values convert into their scalar type (singleton types). Numbers never convert on their own.

Structs

struct Name { field: Type, ... } declares a nominal struct. A field may have a default (port: i32 = 80) and may be marked pub. A struct literal gives every field a value, either written or from its default; nothing is zero-filled. Guide 03 covers literals, defaults, pub, and the inferred literal _{ ... }.

struct Name { ... } is short for type Name = struct { ... }, and the same is true of enum and interface.

A struct { ... } written in type position without a name is anonymous, and its identity is structural: two anonymous struct types with the same field names and types are the same type.

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con p: struct { x: i32, y: i32 } = _{ x: 1, y: 2 }
    con q: struct { x: i32, y: i32 } = p
    println(q.y)   // prints 2
    return Ok(0)
}

A struct type returned by a generic function takes its identity from the known arguments: Box(i32) is the same type everywhere it is written, and Box(i64) is a different one (known values).

Enums

enum Name { Variant, ... } declares a nominal enum: a closed set of variants with unique names, each with zero or more payload values.

Vyi
struct Point { x: i32, y: i32 }

enum Shape {
    Dot,
    Circle(i32),
    Rect(i32, i32),
    Marker(Point),
}
  • A variant is constructed by calling it, Shape.Circle(5), or by its bare name, Circle(5), where the expected type names the enum (expressions, enum construction).
  • match takes an enum apart. It must cover every variant, and it binds the payloads (patterns). An enum without payloads also works as a switch subject.
  • == and != are built in when every payload type compares with ==. The built-in comparison uses each payload type's ==, including a struct's @eq method. A payload type without == leaves the enum without it, and the error names that type. An @eq on the enum itself replaces the built-in comparison (guide 13).

Optional and Result, the types behind ?T and E!T, are ordinary enums from @core, and Some, None, Ok, and Err are ordinary variants.

Interfaces

interface Name { fn (n: ~Name) method() R, ... } declares a set of method signatures. A type satisfies an interface when methods matching every signature are found for it where the value converts to the interface. There is no implements declaration.

A pointer converts to an interface type: con s: Speaker = &dog. The methods are looked up at that conversion, in scope first and then in the type's pocket, and the interface value keeps the ones it found.

Vyi
import { println } from "@fmt"

interface Speaker {
    fn (s: ~Speaker) volume() i32,
}

struct Dog { bark: i32 }

fn (d: Dog) volume() i32 { return d.bark }

fn main() !u8 {
    con rex = Dog{ bark: 9 }
    con s: Speaker = &rex
    println(s.volume())   // prints 9
    return Ok(0)
}

An interface type goes anywhere a type goes: a parameter, a field, a return type. Guide 12 covers the model, and methods and dispatch has the lookup rules.

Tuples

(T, U, ...) is a tuple type: positional, with no declaration, and structural, so two tuple types with the same element types are the same type. Elements are read by position, t.0, t.1, and nested tuples chain, t.0.1.

Vyi
import { println } from "@fmt"

fn minMax(a: i32, b: i32) (i32, i32) {
    if a < b { return (a, b) }
    return (b, a)
}

fn main() !u8 {
    con range = minMax(9, 4)
    println(range.0)   // prints 4
    println(range.1)   // prints 9
    return Ok(0)
}

The empty tuple () is the unit type: one value, (), and no size. A function with no return type returns (). There is no void, and () works wherever a type does: ()!T is a result whose error case carries no data.

Structural unions

A | B | C is a structural union: a value that is exactly one of the member types. There is no wrapper and no variant names; the member types are the cases. There is no union keyword; name a union with a type binding.

Vyi
import { println } from "@fmt"

type Id = i32 | [*con]u8

fn describe(id: Id) [*con]u8 {
    return match typeof id {
        i32:      "number",
        [*con]u8: "name",
    }
}

fn main() !u8 {
    println(describe(41))      // prints number
    println(describe("ada"))   // prints name
    return Ok(0)
}
  • A member converts to the union without being written. A value of i32 is an i32 | [*con]u8 wherever the union is expected, including as an argument. A function with a union parameter is compiled once and takes the union; to get a separate version per argument type, use a _ or known parameter.
  • A union converts to a wider union when its members are a subset of the wider one's. The value keeps the member it holds. Any other union is a type error:

```vyi-error fn main() !u8 { con small: i32 | u8 = u8(1) con big: bool | i32 = small // error: this value has type u8, but the binding is declared bool | i32 return Ok(0) } ```

  • A union is taken apart by its member type, with match typeof u or the binding form if v: T = u. Inside the arm the value has that member type. A match on the union value itself is an error.
  • Narrowing follows the code. In a function body, a binding known to hold one member is read as that member: after a test, after an initialiser (con a: i32 | bool = 7 holds an i32), or after an assignment. Where paths join it holds the union of what each path holds, and taking a mut's address ends what the compiler knows. The binding's storage keeps the declared type. Patterns, narrowing has the full rules.
  • == and != come from the members. u == x, with x a value of a member type, is true when u holds that member and it equals x. u == w, with both of the same union type, is true when they hold the same member and those values are equal. != is the negation. Each comparison uses the member type's own ==, built in or from @eq, so a member without == can't be compared, and neither can an operand that is neither the union nor a member:

```vyi import { println } from "@fmt"

fn lookup(n: i32) i32 | bool { if n > 0 { return n } return false }

fn main() !u8 { con found = lookup(7) con missing = lookup(0) println(found == 7) // prints true println(found == false) // prints false println(found == missing) // prints false return Ok(0) } ```

```vyi-error fn lookup(n: i32) i32 | bool { if n > 0 { return n } return false }

fn main() !u8 { con found = lookup(7) if found == 2.5 { return Ok(1) } // error: this operand of == has type f64, where i32 | bool is expected return Ok(0) } ```

  • A union can be a switch subject, since each arm is an == comparison: switch found { 7: ..., false: ..., default: ... }. It needs default: unless every member is a singleton type (singleton types).

An inferred error type is a union too: !T gets the smallest union of the error types the body produces (error model).

Optionals and error unions

WrittenSame type asHolds
?TOptional(T)a T, or nothing
E!TResult(E, T)an E error, or a T
!TResult(_, T)a T, or one of the errors the body produces
E!Result(E, ())an E error, or success with no value
!Result(_, ())one of the errors the body produces, or success with no value

Optional(T) has the variants Some(T) and None; Result(E, T) has Ok(T) and Err(E). Both are ordinary enums from @core, and every file sees them without an import. A value is always wrapped explicitly: Some(x), Ok(n), Err(e), and Ok(()) for a bare !. A plain T never becomes an optional or a result on its own. You take them apart like any enum, with match or if Some(v) = o, or with try and catch (expressions).

Vyi
import { println } from "@fmt"

fn half(n: i32) ?i32 {
    if n % 2 != 0 { return None }
    return Some(n / 2)
}

fn main() !u8 {
    println(half(10) catch 0)   // prints 5
    println(half(7) catch 0)    // prints 0
    return Ok(0)
}

The short spelling and the full one are the same type, so values move between them freely: an Optional(i32) binding can hold a ?i32 value.

The error type E in E!T can be any type, including a union, which takes parentheses when written in place: (NetErr | ParseErr)!i32. How !T infers its error type, the rule that try stays in one channel, and how error types widen are in the error model reference. Guide 07 introduces them.

Pointers

Every pointer type says whether it can write. A bare *T is not a type; in a pattern it is a type pattern matching either kind.

FormMeaning
*mut Ta pointer to a T you can write through
*con Ta pointer to a T you can only read through
?*mut T, ?*con Ta pointer that may be absent: an ordinary optional
*c_ptr Ta C pointer (below)
  • &x takes an address and *p dereferences.
  • A *mut T converts to a *con T without being written; a *con T never converts to a *mut T.
  • A pointer is never null; absence is ?*mut T or ?*con T. Pointers support only == and !=; there is no pointer arithmetic.
  • Field access, a method call, and a pattern look through one level of pointer: p.x, not (*p).x.
  • A pointer can't outlive what it points at. A pointer into a function's frame or a block can't be returned or stored anywhere that outlives it. The memory model and guide 09 have the rules.
Vyi
import { println } from "@fmt"

fn bump(score: *mut i32) { *score += 1 }

fn main() !u8 {
    mut score = 41
    bump(&score)
    con view: *con i32 = &score
    println(*view)   // prints 42
    return Ok(0)
}

C pointers

*c_ptr T is the pointer of the C boundary, with C's rules: it may be null (address 0), p + n moves it n elements, and indexing it is unchecked. It comes from a C declaration, from a strict pointer assigned to it, or from @core's cPtrOf. Field access, patterns, and value-receiver method calls look through it one level, as through a strict pointer; a pointer-receiver method can't be called through it. Guide 15 covers it.

Arrays

FormMeaning
[N]TN elements, held by value; N is part of the type, so [3]i32 and [4]i32 differ
[*con]T, [*mut]Tan array pointer: a pointer and a length, in one value
*mut [N]T, *con [N]Ta pointer to a fixed array; the length is in the type

A fixed array [N]T is a value: assigning it copies every element. N is a known value; a length known only at run time lives in an array pointer. A literal writes the type and then the elements, [3]i32[10, 20, 30], and [N]T[] fills every element with zeros. arr.len is N, an i32 known value (memory model, fixed arrays).

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con prices = [3]i32[10, 20, 30]
    con empty = [4]u8[]
    println(prices[2])    // prints 30
    println(empty[0])     // prints 0
    println(prices.len)   // prints 3
    return Ok(0)
}

An array pointer [*con]T or [*mut]T is a view of elements stored elsewhere. A string literal is a [*con]u8, and allocators return [*mut]T.

  • xs.len is the number of elements.
  • xs[i] is bounds-checked. An index counts from the start, so the last element is xs[xs.len - 1].
  • xs.ptr is the raw address, for C.
  • Slicing, xs[a..b], gives another view of the same elements (expressions, indexing).

The array shapes convert into each other with a cast:

CastResult
[*mut]T(&arr)a view of the fixed array arr; the length comes from its type
*mut [N]T(view)a pointer to the view's elements as a fixed array; the length is not checked
[N]T(view)a copy of the view's first N elements
Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut scores = [3]u8[1, 2, 3]
    con view = [*mut]u8(&scores)
    con saved = [3]u8(view)
    view[0] = 9
    println(scores[0])   // prints 9
    println(saved[0])    // prints 1
    return Ok(0)
}

A pointer cast describes the same storage differently and trusts you: *mut [4]u8(view) assumes view.len is at least 4. The value cast copies. To narrow a view safely, slice it (view[..4]), which is bounds-checked.

Function types

fn(T, U) R is the type of a function value: the parameter types in parentheses, then the result type; with no result type it returns (). Parameter names may be written as labels and don't change the type.

Vyi
import { println } from "@fmt"

type Discount = fn(price: i32) i32

fn checkout(price: i32, apply: Discount) i32 {
    return apply(price)
}

fn halfOff(price: i32) i32 { return price / 2 }

fn main() !u8 {
    println(checkout(80, halfOff))                     // prints 40
    println(checkout(80, (p: i32) i32 => p - 10))      // prints 70
    return Ok(0)
}
  • A named function and an arrow expression are both values of a function type.
  • Two function values with the same signature have the same type, whatever they capture.
  • A closure value points at its instance, the values it captured, which lives where the closure is written. A closure can outlive that scope only by being put into an allocator (memory model, guide 04). A named function, or a closure that captures nothing, has no instance.
  • *closure is the instance itself: an immutable value whose type no other closure has. It is written only where the compiler knows which closure it is (the literal, or a con bound directly to one), and typeof *closure names its type. A pointer to an instance converts to the closure's function type, so alloc.put(*closure) gives a closure that lives as long as the allocator.
  • A function type's result can't infer its error type: !T there must name the error type, since there is no body to infer from (error model).

type and any

type is the type whose values are types. A type is an ordinary known value: bind it (type Id = u32, con T: type = i32), pass it to a known parameter, return it from a function (that is how generics work), and compare it or switch on it. A switch over a type needs default:, because the set of types is open. The known values reference has the rules.

A type declaration is a con binding, hoisted within its scope (a block, a function, or a file). type Id = u32 makes a new binding Id whose value is the type u32; it does not make a new type. A value declared as an Id is a u32, typeof it is u32, and an Id and a u32 convert both ways without a cast. The binding still carries its own methods: a method defined beside Id is in Id's pocket and applies to a value whose written type is Id, never to a plain u32 (scope and the pocket, methods on a type binding).

any is the type every value converts to. A value converted to any keeps no record of its own type: typeof it is any. A function that acts on its argument's type takes a _ parameter instead, which makes a separate version of the function per argument type:

Vyi
import { println } from "@fmt"

fn kind(v: _) [*con]u8 {
    return match typeof v {
        i32:     "number",
        bool:    "flag",
        default: "other",
    }
}

fn main() !u8 {
    println(kind(5))      // prints number
    println(kind(true))   // prints flag
    return Ok(0)
}

An inferred error type is never any: !T gets its error type from the body.

Singleton and known-value types

A known value written where a type goes is the singleton type that holds exactly that value. Unions of them make a finite set that switch can cover completely:

Vyi
import { println } from "@fmt"

type Mode = "fast" | "slow"

fn delay(mode: Mode) i32 {
    return switch mode { "fast": 1, "slow": 20 }
}

fn main() !u8 {
    println(delay("slow"))   // prints 20
    return Ok(0)
}
  • Integers, strings, chars, and bools all work: 1 | 2, "start" | "stop", 'a' | 'b', true.
  • A value fits a singleton type when the compiler can see it is that value. A known "slow" is a Mode; a [*con]u8 known only at run time is not, even if it holds "slow":

```vyi-error type Mode = "fast" | "slow"

fn delay(mode: Mode) i32 { return 1 }

fn main() !u8 { mut choice: [con]u8 = "slow" con d = delay(choice) // error: argument 1 has type [con]u8, expected "fast" | "slow" return Ok(0) } ```

  • A singleton value converts to its scalar type: with type Two = 2, a Two can be added to an i32.
  • Singleton unions narrow as code runs: an == or != test, or a binding form, removes members for the code after it (patterns, narrowing).

A range type lo..hi holds an integer from lo up to, but not including, hi. A value fits it by the same rule, and if name: lo..hi = n tests a run-time value against a range and narrows it:

Vyi
import { println } from "@fmt"

fn grade(score: 0..101) [*con]u8 {
    if top: 90..101 = score { return "A" }
    return "below A"
}

fn main() !u8 {
    println(grade(95))   // prints A
    println(grade(60))   // prints below A
    return Ok(0)
}

The _ inference placeholder

_ in a type position is a hole the compiler fills. It works as a parameter type, a return type, a binding's type, and a generic argument at any depth. It becomes the smallest union of the types the code puts into it: one type gives that type, and none is a compile error at the _.

Vyi
import { println } from "@fmt"

fn double(n: i32) _ {
    return n * 2
}

fn apply(g: fn(i32) i32, x: i32) i32 { return g(x) }

fn main() !u8 {
    con inc: fn(i32) i32 = (x: _) _ => x + 1
    println(double(4))                       // prints 8
    println(inc(10))                         // prints 11
    println(apply((y: _) i32 => y * 3, 5))   // prints 15
    return Ok(0)
}

double's result type comes from its return; inc's parameter and result come from the declared type; the arrow passed to apply gets its parameter type from apply's parameter.

A bare !T uses the same mechanism: it is _!T, with the error type filled from the body (error model). So does inferring a generic argument, as in max(_, 3, 7) (known values). _ also appears in two places that are not type inference: the inferred struct literal _{ ... } (expressions) and the discard in patterns (patterns).