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.
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.
First, define a Person struct.
package main
import (
"fmt"
)
// Define the Person struct
type Person struct {
FirstName string
LastName string
Age int
}
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
}
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)
}
Person Struct:
Person struct has three fields: FirstName, LastName, and Age.GetDetails Method:
GetDetails method is defined on the Person struct. It returns two values: a string (fullName) and an int (age).main, an instance of the Person struct is created and initialized.GetDetails method is called, and its return values are captured in the fullName and age variables.The output of the above code will be:
Full Name: John Doe
Age: 30