October 2015
Beginner to intermediate
400 pages
14h 44m
English
Functions are first-class values in Go: like other values, function values have types, and they may be assigned to variables or passed to or returned from functions. A function value may be called like any other function. For example:
func square(n int) int { return n * n }
func negative(n int) int { return -n }
func product(m, n int) int { return m * n }
f := square
fmt.Println(f(3)) // "9"
f = negative
fmt.Println(f(3)) // "-3"
fmt.Printf("%T\n", f) // "func(int) int"
f = product // compile error: can't assign f(int, int) int to f(int) int
The zero value of a function type is nil. Calling a nil
function value causes a panic:
var f func(int) int f(3) // panic: ...
Read now
Unlock full access