Golang Tutorial
Fundamentals
Control Statements
Functions & Methods
Structure
Arrays & Slices
String
Pointers
Interfaces
Concurrency
Go has first-class support for returning multiple values from a function, which is particularly useful for returning both a result and an error from a function, among other things. Let's dive into a tutorial on how to utilize this feature:
Here's a simple example of a function that returns two int
values:
package main import "fmt" func getDimensions() (int, int) { return 5, 10 } func main() { width, height := getDimensions() fmt.Println("Width:", width, "Height:", height) // Width: 5 Height: 10 }
It's a common Go idiom to return a result along with an error. This allows the caller to check the error before processing the result:
package main import ( "fmt" "errors" ) func divide(x, y float64) (float64, error) { if y == 0.0 { return 0, errors.New("division by zero") } return x / y, nil } func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Result:", result) } }
Go supports named return values. This can be handy for documentation purposes, and it allows you to use the return
keyword without specifying the values:
func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return // No need to specify x and y } func main() { a, b := split(17) fmt.Println(a, b) // 7 10 }
If you're not interested in all the return values from a function, you can ignore specific returned values using the blank identifier (_
):
func getValues() (int, int, int) { return 1, 2, 3 } func main() { x, _, z := getValues() fmt.Println(x, z) // 1 3 }
Functions can return values of different types. This is often seen with a result and an error, but it can be any type combination:
func userInfo() (string, int, bool) { return "Alice", 30, true } func main() { name, age, isActive := userInfo() fmt.Println("Name:", name, "Age:", age, "Active:", isActive) // Name: Alice Age: 30 Active: true }
Returning multiple values from functions in Go provides a lot of flexibility. It's especially useful for error handling, but there are many other use cases as well. Ensure you handle the returned values properly and check for errors when necessary to write robust Go programs.
Functions with Multiple Return Values in Golang:
package main import "fmt" func divideAndRemainder(a, b int) (int, int) { quotient := a / b remainder := a % b return quotient, remainder } func main() { q, r := divideAndRemainder(10, 3) fmt.Println("Quotient:", q, "Remainder:", r) }
Named Return Values in Golang Functions:
package main import "fmt" func addAndMultiply(a, b int) (sum, product int) { sum = a + b product = a * b return } func main() { resultSum, resultProduct := addAndMultiply(3, 4) fmt.Println("Sum:", resultSum, "Product:", resultProduct) }
Destructuring Multiple Return Values in Golang:
package main import "fmt" func divideAndRemainder(a, b int) (int, int) { quotient := a / b remainder := a % b return quotient, remainder } func main() { result := divideAndRemainder(10, 3) q, r := result // Destructuring fmt.Println("Quotient:", q, "Remainder:", r) }
Error Handling with Multiple Return Values in Golang:
package main import ( "fmt" "errors" ) func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Result:", result) } }
Golang Function Returning a Slice and an Error:
package main import ( "fmt" "errors" ) func generateNumbers(count int) ([]int, error) { if count < 0 { return nil, errors.New("negative count") } numbers := make([]int, count) for i := 0; i < count; i++ { numbers[i] = i + 1 } return numbers, nil } func main() { numbers, err := generateNumbers(5) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Numbers:", numbers) } }
Working with Functions That Return Multiple Types in Golang:
package main import "fmt" func performOperation(a, b int, add bool) interface{} { if add { return a + b } return a - b } func main() { result := performOperation(3, 4, true) fmt.Println("Result:", result) }
Structs and Functions Returning Multiple Values in Golang:
package main import "fmt" type Result struct { Sum int Product int } func addAndMultiply(a, b int) Result { return Result{ Sum: a + b, Product: a * b, } } func main() { result := addAndMultiply(3, 4) fmt.Println("Sum:", result.Sum, "Product:", result.Product) }
Examples of Functions Returning Multiple Values in Golang:
package main import "fmt" func mathOperations(a, b int) (sum, difference, product int) { sum = a + b difference = a - b product = a * b return } func main() { s, d, p := mathOperations(5, 3) fmt.Println("Sum:", s, "Difference:", d, "Product:", p) }