Compiler in Rust (lexer, parser, checker, C codegen), maps, chars, dino fmt, dino lsp (diagnostics, formatting, outline, definition, hover, completion, signature help), docs, examples, VS Code/Vim files. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2.5 KiB
4. Functions
func add(a: int, b: int): int {
return a + b
}
func greet(name: string) { // no result: nothing after the parentheses
print("hi", name)
}
func main() {
print(add(2, 3))
greet("Ada")
}
5
hi Ada
Names in a row can share a type: func area(w, h: float): float.
Several results
A function can return more than one value. The most common use is a value and an error.
func divide(a, b: int): (int, error) {
if b == 0 {
return 0, error("cannot divide by zero")
}
return a / b, nil
}
func main() {
var q, err = divide(7, 2)
print(q, err)
var _, err2 = divide(1, 0)
print(err2)
}
3 nil
cannot divide by zero
More in Errors and nil.
Parameters are safe
A parameter is a copy as far as you can tell: changing it inside never changes the caller's variable. (When a function only reads a parameter, the compiler passes it without copying, so big lists are free to pass around.)
func grow(xs: []int): []int {
xs.push(99)
return xs
}
func main() {
var a = [1, 2]
var b = grow(a)
print(a, b)
}
[1, 2] [1, 2, 99]
Functions are values
A function has a type like func(int): int. You can store it, pass it and return it.
func double(x: int): int { return x * 2 }
func apply(f: func(int): int, x: int): int {
return f(x)
}
func main() {
print(apply(double, 4))
var triple = func(x: int): int { return x * 3 }
print(apply(triple, 4))
print(apply(x => x + 1, 4)) // short form
}
8
12
5
Short lambdas
x => x * 2 and (a, b) => a + b are shorthand for a one-expression function. The types
come from where it is used, so it works where Dino already knows what function is expected
(a parameter, a typed variable, a struct field, or another argument of a generic function).
The short form is one expression; for several statements use the long func(x: int): int { }.
Closures remember
A function written inside another can use the variables around it. It copies them when it is created and keeps its own copy from then on.
func make_counter(): func(): int {
var n = 0
return func(): int {
n += 1
return n
}
}
func main() {
var next = make_counter()
print(next(), next(), next())
var offset = 10
var add = func(x: int): int { return x + offset }
offset = 99 // the closure keeps its own 10
print(add(1))
}
1 2 3
11
Next: Lists and maps