Function Examples
package main import "fmt" /* * Just a bunch of small functions showing different features. */ /* * Variables are passed by value. Slices, too, though the copy continues * to refer to the original array */ func passing(i int, d1 float64, d2 float64, sl []int) { i = 10 d1, d2 = d2, d1 for j := 0; j < len(sl); j += 2 { sl[j] = 99 } } /* * Simply take the maximum of two integers, return that value. Return * type comes at the end of the signature. */ func max_of_two(a int, b int) int { if a > b { return a } else { return b } } /* * Return the maximum value in an array of integers. Instead of giving a value * on a return statement, you may name the return value, and the function * returns whatever that variable as at time of return, explicit or not. */ func slice_max(data []int) (max int) { // Make sure there's something to take. if len(data) < 1 { panic("Attempt to take the max of nothing") } // Initially, the max is the first one, then scan the rest for // something bigger. Slices are passed by value (but not the // their underlying arrays), so changing data will not effect the // slice in the caller. max = data[0] data = data[1:] for _,d := range data { if d > max { max = d } } return } /* * Return both the minimum and maximum of an arbitrary list of arguments. * The ... notation is allowed only for the last argument, and specifies that * a group of arguments should be treated as an array. This function * returns two values. */ func min_max(data ...int) (min int, max int) { // Make sure there's something to take. if len(data) < 1 { panic("Attempt to take the extremes of nothing") } // Initially, the min and max are the first one, then scan the rest for // things larger and smaller. min = data[0] max = data[0] data = data[1:] for _,d := range data { if d > max { max = d } if d < min { min = d } } return } /* * Call 'em all */ func main() { // Passing things doesn't change things, except for sliced array. a := 18 b := 8.34 c := -12.4918 a1 := []int { 3, 9, 11, 3, 17, 34 } passing(a,b,c,a1[:]) fmt.Printf("a = %d b = %g c = %g { ", a, b, c) for _,v := range a1 { fmt.Printf("%d ", v) } fmt.Print("}\n") // Well, it's boring but we need to call it. fmt.Println("max_of_two:",max_of_two(3,8), max_of_two(7,-3), max_of_two(-8,-20), max_of_two(15,10)) // Maximum of a slice. Need something to slice. a2 := []int { 3, 8, 1, 33, -6, 9, 11, 23, 10, 39, 8 } fmt.Println("slice_max:", slice_max(a1[:]), slice_max(a2[:])) // Send any number of values and get two back. min, max := min_max(3, 9, -2, 10, 5, 22, 1, 5) fmt.Printf("min_max(1): %d..%d\n", min, max) // Can also send the slice in place of a an actual list. min, max = min_max(a2[:]...) fmt.Printf("min_max(2): %d..%d\n", min, max) }