Skip to content

Docs/Language/Types

Types

Primitives, compound types, custom types, and the standard library types.

~4 min read

On this page

Primitive types

Integers:   i8  i16  i32  i64  i128   u8  u16  u32  u64  u128
Floats:     f32  f64
Boolean:    bool
Text:       str (owned, immutable text; literals are str), &str (borrowed), String (String::from)
Never:      ! (a function that never returns)

An unannotated val/var initialised from integer literals is an i64; a literal given to a typed place must fit that type (var x: u8 = 300 is an error). There are no literal suffixes (42i64 does not parse) and no char, usize or isize types: a character literal such as 'A' is an integer. A function with no -> returns nothing.

Compound types

[T; N]          // fixed-size array: [2, 3, 5]
(T1, T2)        // tuple: read it by destructuring, val (a, b) = t;
Vec<T>          // growable array
HashMap<K, V>   // hash map: str or integer keys
fn(i64) -> i64  // function type

Custom types

struct Point {
    x: f64,
    y: f64,
}

enum Shape {
    Circle(i64),             // variant with data
    Rect(i64, i64),
    Empty,                   // unit variant
}

type Score = i64;            // type alias

fn area(s: Shape) -> i64 {
    return match s {
        Shape::Circle(r) => 3 * r * r,
        Shape::Rect(w, h) => w * h,
        Shape::Empty => 0,
    };
}

fn main() -> i64 {
    val p = Point { x: 1.5, y: 2.0 };
    val best: Score = area(Shape::Rect(3, 4));
    println(p.x);                    // 1.5
    println(best);                   // 12
    println(area(Shape::Circle(2))); // 12
    return 0;
}

Box<T> puts a value on the heap, which makes recursive types work:

enum Expr {
    Num(i64),
    Add(Box<Expr>, Box<Expr>),
}

fn eval(e: Box<Expr>) -> i64 {
    match e {
        Expr::Num(n) => { return n; }
        Expr::Add(a, b) => { return eval(a) + eval(b); }
    }
}

fn main() -> i64 {
    val two = Box::new(Expr::Num(2));
    val three = Box::new(Expr::Num(3));
    println(eval(Box::new(Expr::Add(two, three))));   // 5
    return 0;
}

Generic enums of your own work, as do core’s Option<T> and Result<T, E>; a literal of a generic struct of your own works on the main branch since Nov 15, and is rejected by the v0.8.0 installer (see Traits & Generics).

Layout and hardware access

use volatile;

@repr(C)                     // C field order and padding
struct EpollEvent {
    events: u32,
    data: u64,
}

@packed                      // no padding
struct UdpHeader {
    src_port: u16,
    dst_port: u16,
    length: u16,
    checksum: u16,
}

fn led_on() {
    val reg = Volatile::new(0x3F200034);   // memory-mapped register
    reg.store32(1);                         // never optimized away
}

Standard library types

TypePurpose
Option<T>Option::Some(x) or Option::None
Result<T, E>Result::Ok(x) or Result::Err(e)
Vec<T>Growable array
StringText with methods (String::from("..."))
HashMap<K, V>Hash map with string or integer keys
Box<T>Heap value
Rc / ArcReference counting (use rc;), i64 payload

Write the variant with its type (Option::Some(4)) when you build a value. In a pattern, Some(v) works without the enum name, but a bare None is a new variable that matches anything: write Option::None. rc_new, rc_clone (count + 1), rc_drop (count − 1, frees at 0), rc_get and rc_count manage an Rc; the arc_* functions do the same with an atomic count. A set of i64 values is Set in stdlib/collections.fd.

Built-in methods

fn main() -> i64 {
    val s = String::from("  Hello,World  ");
    val t = s.trim();
    println(t);                          // Hello,World
    println(t.contains("World"));        // true
    println(t.split(",").len());         // 2
    println(t.to_uppercase());           // HELLO,WORLD
    println(t.replace("World", "Fid"));  // Hello,Fid
    println(String::from("42").parse_int() + 1);   // 43

    var v: Vec<i64> = Vec::new();
    v.push(3); v.push(1); v.push(2);
    v.sort();
    println(v.get(0));                   // 1
    println(v.contains(3));              // true

    var m: HashMap<str, i64> = HashMap::new();
    m.insert("a", 1);
    println(m.get("a"));                 // 1
    println(m.get_or("z", 7));           // 7

    var ages: HashMap<i64, i64> = HashMap::new();
    ages.insert(7, 31);
    println(ages.get(7));                // 31
    return 0;
}
  • String: len, is_empty, contains, starts_with, ends_with, trim, split, replace, to_uppercase, to_lowercase, parse_int, find, rfind, repeat, clone. A plain str uses functions instead: str_len(s), str_contains(s, x).
  • Vec: push, pop, len, get, set, insert, remove, contains, reverse, first, last, extend, truncate, sort, clear, clone.
  • HashMap: insert, get, get_or, contains, remove, len, is_empty, keys, values, clear, clone. Keys are strings or integers; 0 and -1 are ordinary keys, and two specific 64-bit values are reserved (inserting one panics).

Report an issue