Skip to content
Sword

Functions

func add(a int, b int) int {
return a + b
}
func main() int {
return add(20, 22)
}

Types come after names, as in Go. A function with no result just omits it. When several parameters share a type, write it once:

func area(w, h u64) u64 {
return w * h
}

A last parameter can gather whatever is left:

func total(label string, xs ...i64) i64 {
mut sum i64 = 0
for i in 0..xs.len {
sum += xs[i]
}
return sum
}
func main() int {
return int(total("a", 20, 22))
}

Inside the function xs is an ordinary []i64. Gathering ...any is how Printf accepts a mixed list; passing an already-gathered list on to another such function is written f(xs...).

Parameters are immutable too. When a function needs to write through one, the parameter says so, and the caller has to have that permission to give away:

func double(mut xs []i64) {
for i in 0..xs.len {
xs[i] *= 2
}
}
func main() int {
mut values := [4]i64{1, 2, 3, 4}
mut view := values[..]
double(view)
return int(view[3])
}

Drop the mut from view and the call fails to compile: handing a value to a mut parameter is granting write access, and only something you can write can grant it. Copying it into a mut binding does not get around that: the copy can be reassigned, but what it reaches is still the memory view could only read.