Functions
A function has a name, parameters with type annotations, an optional return type, and a body.
fn to_fahrenheit(celsius: float64) -> float64 { celsius * 9.0 / 5.0 + 32.0}Parameter types are required. The return type can be omitted, in which case it defaults to ().
The last expression in the function body is the return value. Use return for early exits.
fn first_positive(nums: Slice<int>) -> Option<int> { for n in nums { if n > 0 { return Some(n)early return value } }
Nonereturn value}Generic functions
Section titled “Generic functions”A generic function features type parameters in its signature:
fn pick_random<T>(items: Slice<T>) -> Option<T> {declaredusedused if items.is_empty() { return None } items.get(rand.IntN(items.length()))}fn swap<A, B>(pair: (A, B)) -> (B, A) { (pair.1, pair.0)}At each callsite, the arguments fill in the type parameters:
let n = pick_random([1, 2, 3])T is intlet s = pick_random(["a", "b"])T is stringlet swapped = swap((1, "one"))A is int, B is stringWrite permission in parameters
Section titled “Write permission in parameters”Only a mut parameter can write to the caller’s data:
fn total(items: Slice<int>) -> inttotal cannot write to itemsfn sort(items: mut Slice<int>)sort can write to itemsA writable value can be passed to a read-only parameter, but a read-only value cannot be passed to a writable one.
let mut scores = [72, 95, 88]let prices = [12, 5, 30]
let sum = total(scores)writable value, read-only parametersort(scores)writable value, writable parametersort(prices)error: prices was declared without mutParameters are read-only. To change one, copy it into a let mut binding with the same name.
fn digits(n: int) -> int { let mut n = nmutable copy of n let mut count = 1 while n >= 10 { n /= 10 count += 1 } count}Lambdas
Section titled “Lambdas”Lambdas are anonymous inline functions.
let is_even = |n: int| n % 2 == 0let full_name = |first: string, last: string| f"{first} {last}"let timer = time.AfterFunc(5 * time.Second, || fmt.Println("timed out"))A block body allows multiple statements:
let describe = |n: int| { let kind = if n % 2 == 0 { "even" } else { "odd" } f"{n} is {kind}"}A lambda can omit a parameter type when the context sets it:
fn passing(scores: Slice<int>) -> Slice<int> { scores.filter(|s| s >= 50)int}Lambdas can capture variables from the enclosing scope. A write inside the lambda changes the outer variable:
let mut calls = 0let log = |message: string| { fmt.Println(message) calls += 1}
log("start")log("stop")calls2Iterators
Section titled “Iterators”A for loop accepts any Go iter.Seq<T> or iter.Seq2<K, V> value. To write one, return a lambda that takes a yield function. Call yield once per element, and return as soon as yield gives back false:
import "go:iter"
fn count_up(n: int) -> iter.Seq<int> { |yield: fn(int) -> bool| { for i in 0..n { if !yield(i) { return } } }}for i in count_up(1000) { if i == 3 { break }ends the iterator fmt.Println(i)}