Skip to main content

Types

A type declaration takes pub and nothing else. pub makes the type visible to other files. Without it the type belongs to the file that declares it, and that is narrower than its namespace: two files sharing a namespace still cannot see each other's private types.

pub type Point { }

type Internal { }
note

static and external are not modifiers a type accepts, and using one is an error. static belongs on a method, and external on a function.

Fields

note

All fields must be initialized when creating a class.

pub type Person {
pub field name: string;
}
// Usage:
let person = new Person {
name: "Patrik"
};
note

A field cannot be static. A type holds fields for each of its values, and there is nowhere for a shared one to live.

Mutability

A field is immutable once the value is created, the same way a let is. To assign to one afterwards, declare it mut.

pub type Counter {
pub mut field total: i32;
pub field name: string;
}
// Usage:
let counter = new Counter { total: 0, name: "hits" };
counter.total = 1; // ok
counter.name = "no"; // Error: cannot assign to 'name' because it is not mutable

This holds inside the type as well, so a method that writes a field needs that field to be mut.

pub type Counter {
pub mut field total: i32;

pub fn add(amount: i32) -> void {
self.total = self.total + amount;
}
}

Methods

pub type Counter {
pub field value: i32;

pub fn next() -> i32 {
return self.value + 1;
}
}
// Usage:
let counter = new Counter { value: 41 };
let value = counter.next();

self

Inside a method, a field is read by name. self names the value the method was called on, and is only needed when something else has taken the name.

pub type Counter {
pub field value: i32;

pub fn plus(value: i32) -> i32 {
return self.value + value;
}
}

Here value is the parameter and self.value is the field. Without a parameter of that name, value and self.value mean the same thing.

note

self is a reserved word, so it cannot be used as a name. It is an error outside a type, and in a static fn, which has no value to refer to.

Static methods

pub type Counter {
pub field value: i32;

pub static fn zero() -> Counter {
return new Counter { value: 0 };
}
}
// Usage:
let counter = Counter::zero();

Constructors

Mew does not have constructors per se, but uses one or more static methods; by convention called new.

pub type Person {
pub field name: string;

pub static fn new(name: string) -> Person {
return new Person { name: name };
}
}
// Usage:
let person = Person::new("Patrik");
note

A type can only be declared at the top level of a file. There are no types inside functions or inside other types.