Multiple Return Values

GolangGolangBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Go, functions can return multiple values. This feature is commonly used to return both a result and an error value from a function.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Golang`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go/FunctionsandControlFlowGroup -.-> go/functions("`Functions`") subgraph Lab Skills go/functions -.-> lab-15489{{"`Multiple Return Values`"}} end

Multiple Return Values

Complete the swap function to return two input parameters in reverse order.

  • The swap function should take two integers as input parameters.
  • The swap function should return two integers in reverse order.
$ go run multiple-return-values.go
3
7
7

## Accepting a variable number of arguments is another nice
## feature of Go functions; we'll look at this next.

There is the full code below:

// Go has built-in support for _multiple return values_.
// This feature is used often in idiomatic Go, for example
// to return both result and error values from a function.

package main

import "fmt"

// The `(int, int)` in this function signature shows that
// the function returns 2 `int`s.
func vals() (int, int) {
	return 3, 7
}

func main() {

	// Here we use the 2 different return values from the
	// call with _multiple assignment_.
	a, b := vals()
	fmt.Println(a)
	fmt.Println(b)

	// If you only want a subset of the returned values,
	// use the blank identifier `_`.
	_, c := vals()
	fmt.Println(c)
}

Summary

In this lab, you learned how to use multiple return values in Go. By completing the swap function, you were able to swap two integers and return them in reverse order.

Other Golang Tutorials you may like