Skip to content

Structures and Methods

A struct is a custom type that holds several values together under one name. Each value is a field with its own name and type. Fields are private by default, pub makes them visible outside the module.

struct Person {
age: u32,
pub name: String,
}

The construction names every field:

let person = Person { .age = 26, .name = name };

Fields read with dot, writes need a mutable pointer receiver or owned value:

@println("{}", person.age);

Structs take generics, with bounds if needed:

struct Box[T] {
pub inner: *T,
}
struct DisplayBox[T: Display] {
inner: T,
}

Methods can declare their own generics on top of the struct ones:

struct Wrap[T] {
inner: T,
pub fn dup_inner[T: Clone](*const self) T {
return self.inner.clone();
}
}

A struct is Copy only if all its fields are, otherwise it is move-only. A type with Drop cannot be Copy: pick one. If Drop is not implemented explicitly, all fields drop recursively at scope end.

implement Copy : Tag {}
implement Drop : Tag {
fn drop(self) {
@println("drop {}", self.name);
}
}

implement blocks can be generic too:

implement[T] Drop : Box[T] {
fn drop(self) {
free(self.inner);
}
}

Methods live in struct bodies and take self as the first receiver. Self is the struct type itself.

Receiver Mode
self owned value
const self owned, read-only
*self mutable borrow
*const self read-only borrow

Example:

struct Person {
age: u32,
pub fn birthday(*self) {
self.age += 1;
}
}

Static calls go through the type, method calls through the value:

let person = Person.new(26);
person.birthday();