Skip to content

Golang Return Multiple Values: Different Types + Error

Lovely Golang! I like this feature in Go which you can return multiple values from your functions 🙂

Look at the below function definition and you can see that you can have many outputs from one function:

func myFunction() (output1 type, output2 type, output3 type) {
	return output1, output2, output3
}

A simple code example:

package main

import (
	"errors"
	"fmt"
	"log"
)

func greeting(name string) (msg string, err error) {

	if name == "" {
		err := errors.New("the name input is empty")

		return msg, err
	}

	msg = fmt.Sprint("Hello ", name, "!")

	return msg, err
}

func main() {
	g, err := greeting("morteza")

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(g)
}

Leave a Reply

Your email address will not be published. Required fields are marked *