Skip to content

Struct Prototypes

Struct instances use prototypes for fields and implemented methods.

struct User {
name: string
}
let user = User()
user.name = "Martin"
println(user.name)

Use impl to attach methods to a struct.

struct User {
name: string
}
impl User {
fn greet(self: User) string {
return "Hello, " + self.name
}
}
let user = User()
user.name = "Martin"
println(user.greet())

When a function attached to a struct expects the struct instance as its first argument, Nubo binds the current instance automatically.

That means this method:

fn greet(self: User) string {
return "Hello, " + self.name
}

Can be called like this:

user.greet()

Struct prototypes can enforce private fields.

Private fields cannot be modified outside the implementation context.

struct User {
private password: string
name: string
}

Use methods inside impl to control access.

impl User {
fn setPassword(self: User, password: string) void {
self.password = password
}
}

Struct instances can define special prototype hooks.

HookDescription
__string__Controls how the struct is converted to a string.
__clone__Controls how the struct is cloned.
$convoutConverts public fields into a dictionary-like output.

If a struct instance has a __string__ function returning string, Nubo uses it for string conversion.

struct User {
name: string
}
impl User {
fn __string__(self: User) string {
return "User(" + self.name + ")"
}
}

If a struct instance has a __clone__ function, Nubo uses it when cloning.

struct User {
name: string
}
impl User {
fn __clone__(self: User) User {
let copy = User()
copy.name = self.name
return copy
}
}