How to Fix “too many arguments to return” Error in Go

To fix the “too many arguments to return” error in Go, specify what you will return after specifying the input parameters and ensure the number of values you return matches the function’s return type signature”.

The “too many arguments to return” error in Go occurs when you return more values than the function’s return type signature specifies.

Here’s an example of a function that causes the “too many arguments to return” error.

package main

import "fmt"

func example() int {
  a := 1
  b := 2
  return a, b
}

func main() {
  result := example()
  fmt.Println(result)
}

Output

too many return values

To fix the error, update the function’s return type signature to match the number of values you return. In this example, you can return a pair of integers by changing the return type to (int, int).

package main

import "fmt"

func example() (int, int) {
  a := 21
  b := 19
  
  return a, b
}

func main() {
  result1, result2 := example()
  fmt.Printf("Result 1: %d, Result 2: %d\n", result1, result2)
}

Output

Result 1: 21, Result 2: 19

Ensure to handle the returned values properly and update both the function definition and the function call.

Leave a Comment