Go Function Returns: Sending Data Back

Functions in Go can send data back to the calling code using return values. This allows you to create modular and reusable code that produces meaningful results.



Single Return Value

A function can return a single value of a specific data type.

Syntax
func add(x, y int) int {
  return x + y
}
Output
None

Multiple Return Values

Go supports returning multiple values, which is a powerful feature for encapsulating related data.

Syntax
func calculateStats(numbers []int) (int, float64) {
  sum := 0
  for _, num := range numbers {
    sum += num
  }
  avg := float64(sum) / float64(len(numbers))
  return sum, avg
}
Output
None

Named Return Values

You can name the return values, making the code more readable and sometimes allowing for early returns.

Syntax
func calculateStats(numbers []int) (sum int, avg float64) {
  for _, num := range numbers {
    sum += num
  }
  avg = float64(sum) / float64(len(numbers))
  return
}
Output
None

Omitting Return Values

You can omit specific return values using the underscore (_).

Syntax
_, avg := calculateStats(numbers)
Output
None

Returning Pointers

Functions can return pointers to variables, allowing you to modify values indirectly.

Syntax
func increment(x *int) {
  *x++
}
Output
None

Best Practices

  • Use meaningful names for return values.
  • Consider error handling when returning multiple values.
  • Avoid excessive return values.
  • Use named return values for clarity.
  • Use pointers carefully to avoid unexpected behavior.

By effectively using return values, you can create well-structured and reusable functions in your Go code.