Home
Go
func Examples
This page was last reviewed on Mar 9, 2023.
Dot Net Perls
Func. In Go programs we use func to specify functions. With multiple return values, methods can be more clearly written. Return values have names and positions.
We use the "func" keyword in Golang. And it is important to remember that types come after names—the opposite of C-like languages.
Multiple return values. Sometimes a method has no return value. But often we have one or more things to return—new objects, numbers, results.
Detail We specify this method, firstAndLast, has 2 return values. These are (int, int): specified after the argument.
Return We can return 2 arguments by using a return-statement with a comma in it.
Here In main we pass a slice to firstAndLast, and it returns the first and last elements in the slice.
Slice
package main import "fmt" func firstAndLast(items []int) (int, int) { // Return two values. return items[0], items[len(items) - 1] } func main() { data := []int{5, 50, 500, 5000} // Assign values to result of method. first, last := firstAndLast(data) // Display results. fmt.Println(first) fmt.Println(last) }
5 5000
No return value. Here we create a func named "display" that receives 2 arguments of type int. It returns nothing—this is a void method.
Detail Both arguments (apples, oranges) to this method are of type int. The int is specified after the argument name.
package main import "fmt" func display(apples int, oranges int) { // Display count of apples and oranges. fmt.Println(apples) fmt.Println(oranges) } func main() { // Call display method. display(10, 12) }
10 12
Named return values. Optionally we can provide names to return values. In the method, we can use those named values like variables or arguments.
Important The default value for an int return value is 0. So they do not need to be assigned before returning them again.
Here We enhance firstAndLast() so that it sets the "first" and "last" arguments only if the slice has at least two elements.
package main import "fmt" func firstAndLast(items []int) (first int, last int) { // If slice is at least two elements, set first and last. // ... Otherwise, leave the return values as zero. if len(items) >= 2 { first = items[0] last = items[len(items)-1] } return first, last } func main() { // For a zero-element slice, both return values are 0. data := []int{} fmt.Println(firstAndLast(data)) // The first and last values are set. data = []int{9, 8, 7, 6} fmt.Println(firstAndLast(data)) }
0 0 9 6
Func local, argument. A func can be the value in an assignment statement. Here we assign to the variable "f" a func that receives a rune and returns a bool.
Detail We can pass the func variable as an argument to a method (like IndexFunc) that requires a func argument.
Result The func returns true on the comma and space characters. So it returns 3 in both uses.
package main import ( "fmt" "strings" ) func main() { f := func(c rune) bool { // Return true if space or comma rune. return c == ' ' || c == ','; } value := "cat,bird" // Pass func object to IndexFunc method. result := strings.IndexFunc(value, f) fmt.Println(result) value = "cat bird" result = strings.IndexFunc(value, f) fmt.Println(result) }
3 3
Variable arguments. A variadic function accepts a variable number of arguments. We specify this with an ellipsis (three periods) in the argument list, as part of the final argument.
Detail We use the variadic argument with the same syntax as a slice. We can use len(), range and access elements.
package main import "fmt" func PrintSum(name string, values ...int) { sum := 0 // Loop over all variadic arguments and sum them. for i := range(values) { sum += values[i] } fmt.Println(name, sum) } func main() { // Call variable-argument method. PrintSum("cat", 1, 2, 3) PrintSum("dog", 10, 20) PrintSum("ant") }
cat 6 dog 30 ant 0
Defer. The defer keyword is used to specify a function (or expression) that is executed right before a func returns. If the defer func returns nil, a panic will occur.
Tip We use defer to specify error-handing logic, as with the recover() method. But it can be used in other methods (like for cleanup) too.
recover
Here The example() method sets its return value count to 10 in a defer func. This always changes the result to 10.
package main import "fmt" func example() (count int) { defer func() { // Set result to 10 right before the return is executed. count = 10 }() return count } func main() { fmt.Println(example()) }
10
A summary. Multiple return values are useful for concurrency in programs. A complex computation, run on a thread, often has more than one thing to return.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 9, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.