DEV Community

Cover image for golang multiple return
bluepaperbirds
bluepaperbirds

Posted on

1

golang multiple return

Typically a function only returns one variable, but why should that be?

In the Go programming language, functions can return multiple values. This is unlike C, where a function only returns one value. However there are other languages that support multiple return, like Python.

On syntax we can say, the type of return value is written at the end instead of in the beginning. Where in C you would have

int plus(int a, int b) {

In Go the same function would be

func plus(a,b int) (int) {

Multiple return

As I mentioned above, functions in Go can return multiple values.
You can have a function like this:

func swap(x, y string) (string, string) {
    return y, x
}

This function then returns two variables of the type string, but it also takes two parameters of the type string.

You can store the output like this:

a, b := swap("hello", "world")

So if you put that in a program, you would have this:

package main

import "fmt"

func swap(x, y string) (string, string) {
    return y, x
}

func main() {
    a, b := swap("hello", "world")
    fmt.Println(a, b)
}

That gives you new options when programming. You could have a multiply function that returns the input values and the output.

package main

import "fmt"

func multiply(a,b int) (int,int,int) {
    return a,b,a*b
}

func main() {
    a, b, c := multiply(16,13)
    fmt.Println(a,b,c)
}

If you run it you'll see that:

➜  ~ go run example.go
16 13 208

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay