What types can golang functions return?

WBOY
Release: 2024-06-01 12:20:56
Original
444 people have browsed it

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)

What types can golang functions return?

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:

  • Basic types: Such as integer (int), floating point number (float64), Boolean value (bool), string ( string) etc.
  • Combined types: Types derived from basic types, such as arrays, slices, maps, etc.
  • Structure type: Custom data type, which can contain multiple fields, each field has its own type.
  • Interface type: Defines the behavior of a set of methods.
  • Error type: Indicates an error condition. Usually an implementation of the error interface.

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

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
Copy after login

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!

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
Popular Tutorials
More>
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!