Home > Article > Backend Development > How to customize return value type in golang?
In the Go language, you can create custom types to define function return values to enhance flexibility and allow data to be returned in a specific format or structure. Defined with syntax: func functionName() (returnType1, returnType2, ..., returnTypeN) {}, for example, the function GetPerson() can return a custom structure Person containing name and age attributes.
Go custom return value type
In the Go language, we can define the return value of a function by creating a custom type value. This provides greater flexibility, allowing us to return data in a specific format or structure.
Syntax
The syntax of the custom return value type is as follows:
func functionName() (returnType1, returnType2, ..., returnTypeN) { // 函数体 }
Among them:
functionName
is the function name. returnType1
, returnType2
, etc. are lists of return types. Practical Case
Suppose we want to create a function that returns a custom structure containing two attributes (name and age). We can achieve this by:
package main import "fmt" // 自定义结构体 type Person struct { Name string Age int } // 返回自定义结构体的函数 func GetPerson() Person { return Person{ Name: "Alice", Age: 25, } } func main() { // 存储自定义返回值 person := GetPerson() // 访问结构体的属性 fmt.Println("姓名:", person.Name) fmt.Println("年龄:", person.Age) }
Output
姓名: Alice 年龄: 25
In this example, the GetPerson()
function returns Person
Instance of structure. The main function calls the function and stores the return value, then accesses the Name
and Age
properties of the structure.
The above is the detailed content of How to customize return value type in golang?. For more information, please follow other related articles on the PHP Chinese website!