Types and values
The main types are data (a record), enum (a sum whose variants may carry fields) and unions A | B. Methods are written in
impl; a static fn is called as Point.origin(). Inside a method the fields are available by name.
data Point { x: f64; y: f64 }
impl Point {
static fn origin() -> Point => Point{ x: 0.0, y: 0.0 }
fn dist2() -> f64 => x * x + y * y
}
enum Shape {
Circle(r: f64)
Rect(w: f64, h: f64)
Empty
}
fn area(s: Shape) -> f64 pure =>
match s {
Circle(r) => 3.0 * r * r
Rect(w, h) => w * h
Empty => 0.0
}
fn main() io {
let p = Point{ x: 3.0, y: 4.0 }
print("{p.dist2()}")
var names: List<str> = ["ann", "bob"]
names.push("eve")
print("{names.len()} {names}")
let ages: Map<str, i32> = {"ann": 31, "bob": 25}
print("{ages.get("bob") ?? 0} {ages.get("zed") ?? -1}")
print("{area(Shape.Rect(2.0, 5.0))} {area(Shape.Empty)}")
let squares = from n in 1..=5 select n * n
print("{squares.toList()}")
}Output
25.0 3 ["ann", "bob", "eve"] 25 -1 10.0 0.0 [1, 4, 9, 16, 25]
What to read next#
- Ownership and borrowing without explicit lifetimes: §7. A value moves when passed,
clonecopies,&Tborrows. - Refined types (
type Percent = u8 where 0..=90),distincttypes,@derive(Copy, Eq, Ord, Hash, Show): §3 and §4. - Interfaces are structural: any type with the right methods fits (§4.6);
embedand operator overloading are in V.3. - Standard collections and iterators:
std.core.