Home > Article > Backend Development > What types can golang functions return?
Go language functions can return multiple types of values, including: basic types (such as integers, floating point numbers) combination types (such as arrays, slices) structure types (custom types) interface types (behavior definitions) error types (error Situation representation)
Golang function return value type
In the Go language, functions can return various types of values. Some commonly used return value types are listed below:
Practical case:
The following code demonstrates how to define a function that returns multiple return value types:
func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil }
This function accepts Two integer parameters a and b, and returns an integer quotient and an error value. If b is 0, then the quotient is 0 and an error value indicating a divide-by-zero error is returned. Otherwise, the quotient and nil error value are returned.
Usage:
result, err := divide(10, 2) if err != nil { // 处理错误 } fmt.Println(result) // 输出: 5
This example shows how to call the divide function, handle errors based on the resulting value, and print the quotient.
The above is the detailed content of What types can golang functions return?. For more information, please follow other related articles on the PHP Chinese website!