Skip to main content

Methods

methods are functions that are attached to a type

declare them and call them like this

you use the dot . syntax, similarily to members

type Person struct{}

fun (p Person) greet() {
putln("hello")
}

x := Person{}

x.greet()

output: hello

you can also use member expressions inside the method like this

type Person struct {
Name string
}

fun (p Person) greet() {
putln("Hello ${p.Name}")
}

x := Person{
Name: "Ziad"
}

x.greet()

output: Hello Ziad

also exactly like functions they require parameter and return types and allow multiple return types

type Person struct {
Name string
}

fun (p Person) greet(age int) {
putln("Hi ${p.Name} you are {age}")
}

x := Person{
Name: "Ziad"
}

x.greet(13)

output: Hi Ziad you are 13

type Person struct {
Name string
Age int
}

fun (p Person) getInfo() (string, int) {
return p.Name, p.Age
}

x := Person{
Name: "Ziad",
Age: 13,
}

name, age := x.getInfo()

putln(name, age)

output: Ziad 13

disclaimer

pointers and refs are not yet a feature so you can only make the receiver a value copy

which means that it will only adjust what happens inside the function

type Person struct {
Name string
}

fun (p Person) switchName(name string) {
p.Name = name
putln(p.Name)
}

x := Person{
Name: "Zi"
}

x.switchName("Ziad") // Ziad

putln(x.Name) // Zi

output:

Ziad
Zi

since that would usually require something like (p *Person)

fun note!

methods work like normal functions under the hood, but they make their receivers the first parameter

so a method like this

fun (p Person) greet(age int) {
putln("Hi ${p.Name} you are ${age}")
}

would correspond to a function like this

fun greet(p Person, age int) {
putln("Hi ${p.Name} you are ${age}")
}

therefore a method call like this

p := Person{
Name: "Ziad"
}

p.greet(13)

would correspond to a function call like this

p := Person{
Name: "Ziad"
}

greet(p, 13)