How does golang return a structure?

王林
Release: 2024-04-23 14:03:01
Original
605 people have browsed it

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 does golang return a structure?

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", } }
Copy after login

Personis a structure type that contains theName,Age, andGenderfields.

Practical case

Let us create agetPersonInfofunction 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) }
Copy after login

Explanation

In this example, thegetPersonInfofunction receives three parameters and returns aPersonstructure.mainThe function calls thegetPersonInfofunction and prints the returned structure.

Run the example

$ go run main.go {Jane Doe 25 Female}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!