Skip to content

Your own types

A struct groups named fields. Fields are private to the module unless marked pub, so a module can make sure its values are always valid: code elsewhere can only make one through the functions the module offers.

struct Account {
owner: Str
balance: i64
}
impl Account {
fn open(owner: Str) -> Account {
return Account { owner, balance: 0 }
}
fn deposit(&mut self, amount: i64) {
self.balance += amount
}
fn summary(&self) -> Str {
return f"{self.owner}: {self.balance}"
}
}
let mut a = Account.open("Grace")
a.deposit(50)
print(a.summary())
Grace: 50

Methods take &self to read, &mut self to change, or self to consume the value. Calling a &mut self method needs a let mut variable.

An enum is one of several variants, and each variant can carry data.

enum Shape {
Circle(f64)
Rect(f64, f64)
}
fn area(s: &Shape) -> f64 {
match s {
Shape.Circle(r) => return 3.14159 * *r * *r
Shape.Rect(w, h) => return *w * *h
}
}
let shapes = [Shape.Circle(1.0), Shape.Rect(2.0, 3.0)]
for s in &shapes {
print(f"{area(s):.2}")
}
3.14
6.00

A trait names behaviour that several types can share. impl Trait for Type provides it. Prelude traits give your types operators: Add for +, Equal for ==, Order for < and for sorting.

trait Describe {
fn describe(&self) -> Str
}
struct Version {
major: i64
minor: i64
}
impl Describe for Version {
fn describe(&self) -> Str {
return f"v{self.major}.{self.minor}"
}
}
impl Order for Version {
fn compare(&self, other: &Version) -> i64 {
if self.major != other.major {
return self.major.compare(&other.major)
}
return self.minor.compare(&other.minor)
}
}
let mut versions = [Version { major: 1, minor: 10 }, Version { major: 1, minor: 2 }, Version { major: 0, minor: 9 }]
versions.sort()
for v in &versions {
print(v.describe())
}
print(f"{versions[0] < versions[1]}")
v0.9
v1.2
v1.10
true