-1

The following is what I want to achieve

fmt.Println(string(ioutil.ReadAll(res.Body)))

But this throws the following error.

multiple-value ioutil.ReadAll() in single-value context

I know that ioutil.ReadAll() returns the bytes and the error. But I don't want to write an extra line as follows

bytes, _ := ioutil.ReadAll(resp.Body)

Is it possible to just pass the result of ioutil.ReadAll() to fmt.Println() if don't care abut error handling in Go?

1 Answers1

0

If you want it only once, it makes little sense in my opinion. However if this is a common situation and you feel that it improves code readability a lot, try something like:

// perhaps, there's a better name for this
func resultToString(b []byte, _ error) string { 
    return string(b)
}

// and later:
fmt.Println(resultToString(ioutil.ReadAll(res.Body)))

Unfortunately, that's a string-specific function, so for any other type you'll need to duplicate it.

bereal
  • 32,519
  • 6
  • 58
  • 104
  • ioutil.ReadAll actually return bytes, right? So this means that I will have to write similar functions for all types in go. – aswinmprabhu Aug 07 '18 at 13:10
  • @aswinmprabhu `[]byte` indeed, updated the answer. Yes, until Go gets some generic types, you will have to duplicate it for every type you need. – bereal Aug 07 '18 at 13:13
  • 1
    Just as a statement of intent, I'd also change the arguments to `(b []byte, _ error)`. The underscore makes it obvious that the error is going to be ignored – Elias Van Ootegem Aug 07 '18 at 13:20
  • @EliasVanOotegem good point, will update. – bereal Aug 07 '18 at 13:20
  • 2
    I'd be very, very wary of any program that suppresses so many errors that it needs a helper (or multiple helpers) to do it. That's just asking for trouble. – Adrian Aug 07 '18 at 14:43
  • @Adrian valid point, though in testing code redundancy is often pain, also some functions like `json.Marshal` are not likely to return error, even though it's in the signature. – bereal Aug 07 '18 at 15:13