Methods and Receivers
Methods must be declared in the same module as the type.
An immutable receiver is passed efficiently (by reference under the hood for large structs).
Method chaining works when methods return the receiver type.
Static-like functions: use regular functions, e.g. fn new_rect(w f64, h f64) Rect. Newer V also supports fn Rect.new() Rect (static methods), called as Rect.new().
struct Rect {
w f64
h f64
}
fn (r Rect) area() f64 { // value (immutable) receiver
return r.w * r.h
}
fn (mut r Rect) scale(k f64) { // mutable receiver
r.w *= k
r.h *= k
}
fn (r Rect) str() string { // custom string conversion used by println
return 'Rect(${r.w} x ${r.h})'
}
mut r := Rect{w: 2, h: 3}
r.scale(2)
println(r.area())
println(r)