Three ways to return values

July 30, 2024

Return statements

There are three ways to return values from a function with a result type:

Do you know all three off the top of your head?

We’ll be looking at each of them over the coming three days.

  1. The return value or values may be explicitly listed in the “return” statement. Each expression must be single-valued and assignable to the corresponding element of the function’s result type.
func simpleF() int {
	return 2
}

func complexF1() (re float64, im float64) {
	return -7.0, -4.0
}

This is pretty straight forward, and probably the way form that first came to your mind. In fact, if you’re new to Go, you may be surprised to learn that there’s any other way at all!

There’s not a whole lot to say about this particular method. It’s the one that the vast majority of functions use. The most important thing to remember is that the number of return values must match the number of return values in the function signature, and that their types must match (via assignability, as mentioned).

func foo() (int, string, error) {
	return 3 // Invalid, not enough return values

	return "3", "foo", nil // Invalid, the first argument is not assignable to `int`

	return 3, "foo", nil // Valid!
}

One tid-bit I’ll throw in… unlike with input parameters in functions, where a single variadic function is allowed (i.e. ...[]string), this is not permitted for return values:

func foo() (...[]string) {
	var strings []string
	/* some logic */
	return strings...
}

If you want to return a variable number of values from a function, you need to come up with another approach. Probably returning a simple slice is good enough:

func foo() []string {
	var strings []string
	/* some logic */
	return strings
}

Although there are other options. You might return a channel, for example. Or some other form of iterator.

Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe