Structures — Methods — Multiple return values

In Go, functions and methods can return multiple values. This feature is useful for returning additional information, such as error values or multiple computed results, without needing to use out parameters or modify input arguments.

Example: Method Returning Multiple Values

Let's create an example where a method returns multiple values. We'll use a Person struct and create a method that returns the person's full name and age.

Step 1: Define the Struct

First, define a Person struct.

package main

import (
    "fmt"
)

// Define the Person struct
type Person struct {
    FirstName string
    LastName  string
    Age       int
}

Step 2: Define the Method with Multiple Return Values

Create a method for the Person struct that returns the full name and age.

// Method to get the full name and age of the person
func (p Person) GetDetails() (string, int) {
    fullName := p.FirstName + " " + p.LastName
    return fullName, p.Age
}

Step 3: Use the Method

Finally, use the method in the main function.

func main() {
    // Create an instance of Person
    person := Person{
        FirstName: "John",
        LastName:  "Doe",
        Age:       30,
    }

    // Call the GetDetails method and capture the return values
    fullName, age := person.GetDetails()

    // Print the return values
    fmt.Printf("Full Name: %s\\\\n", fullName)
    fmt.Printf("Age: %d\\\\n", age)
}

Explanation

  1. Define the Person Struct:
  2. Define the GetDetails Method:
  3. Use the Method:

Detailed Output

The output of the above code will be:

Full Name: John Doe
Age: 30