28

When trying to use strconv on a variable passed via URL(GET variable named times), GoLang fails on compilation stating the following:

multiple-value strconv.Atoi() in a single-value context

However, when I do reflect.TypeOf I get string as the type, which to my understanding is the correct type of argument.

I have been trying to fix this issue for several hours. I'm new to go and have become pretty frustrated with this problem. I finally decided to ask for help. Any feedback would be appreciated.

func numbers(w http.ResponseWriter, req *http.Request) {
  fmt.Println("GET params were:", req.URL.Query()); 
  times := req.URL.Query()["times"][0]
  time := strconv.Atoi(times)

  reflect.TypeOf(req.URL.Query()["times"][0]) // returns string
}
dead beef
  • 673
  • 2
  • 6
  • 20

2 Answers2

69

The error is telling you that the two return values from strconv.Atoi (int and error) are used in a single value context (the assignment to time). Change the code to:

   time, err := strconv.Atoi(times)
   if err != nil {
      // Add code here to handle the error!
   }

Use the blank identifier to ignore the error return value:

   time, _ := strconv.Atoi(times)
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • Thanks this fixed the issue. It's pretty strange that functions can return more than one type of value in Go though. Does it matter which order time & err are in? – dead beef Apr 29 '16 at 00:37
  • 6
    @deadbeef: multiple returns are one of the basic features of the language. I would suggest at least going through the [Tour of Go](https://tour.golang.org/) to get an idea how the language works – JimB Apr 29 '16 at 00:59
  • @cerise It worked for me. – Vijay Nov 22 '21 at 16:12
12

Although this has been answered and the question is quite old, I thought it would be nice to complement the accepted answer.

When a function returns multiple values as in the question, if any of the value is not needed then they can be discarded by using the blank identifier _ as in the following.

num, _ := strconv.Atoi(numAsString)

This would store the converted number in num but discard the error by assigning it to the blank identifier.

But do note that once a value is assigned to _ it cannot be referenced again. i.e.

num, _ := strconv.Atoi(numAsString)
fmt.Println(_) // won't compile. cannot reference _
Thirumalai Parthasarathi
  • 4,541
  • 1
  • 25
  • 43