Home >Backend Development >Golang >How does golang return a structure?
How to return a structure in Golang? Specify the structure type in the function signature, such as: func getPerson() Person {}. Use the return {} statement inside the function body to return a structure containing the required fields. Struct fields can be base types or other structures.
How to use Golang to return a structure
In Golang, a structure is an aggregate data type that allows you to Related data are grouped together. Returning a structure is a good choice when you need to return data containing multiple fields from a function.
Syntax
To return a structure, you need to specify the structure type in the function signature. For example:
func getPerson() Person { return Person{ Name: "John Doe", Age: 30, Gender: "Male", } }
Person
is a structure type that contains the Name
, Age
, and Gender
fields.
Practical case
Let us create a getPersonInfo
function that returns a structure containing personal information:
package main import "fmt" type Person struct { Name string Age int Gender string } func getPersonInfo(name string, age int, gender string) Person { return Person{ Name: name, Age: age, Gender: gender, } } func main() { person := getPersonInfo("Jane Doe", 25, "Female") fmt.Println(person) }
Explanation
In this example, the getPersonInfo
function receives three parameters and returns a Person
structure. main
The function calls the getPersonInfo
function and prints the returned structure.
Run the example
$ go run main.go {Jane Doe 25 Female}
This example demonstrates how to use Golang to return a structure and can be used when you need to return data containing multiple fields from a function.
The above is the detailed content of How does golang return a structure?. For more information, please follow other related articles on the PHP Chinese website!