13

I'm trying to initialize a struct in Go, one of my values is being which returns both an int and an error if one was encountered converted from a string using strconv.Atoi("val").

My question is : Is there a way to ignore an error return value in Golang?

ts := &student{
    name: td[0],
    ssn: td[2],
    next: students.next,
    age: strconv.Atoi(td[1]),
  }

which gives the error

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

if I add in the err, which i don't want to include in my struct, I will get an error that I am using a method that is not defined in the struct.

anonrose
  • 1,271
  • 3
  • 12
  • 19
  • Ya I looked at that, looks like they're not using the composite literal initialization. – anonrose Mar 15 '16 at 19:10
  • 2
    Yes, it is not used in a composite literal, but that doesn't change the fact that they want to achieve the same goal: to discard the returned 2nd value (error). Please read the answer too which suggests a `MustXXX()` helper function to do just that. – icza Mar 15 '16 at 19:11
  • So there isn't a way to do it in one line? – anonrose Mar 15 '16 at 19:13
  • No. Your options are listed in this answer: [Return map like 'ok' in golang on normal functions](http://stackoverflow.com/a/28487270/1705598). _(Actually you could do it in one line too but that would be uglier - see [this answer](http://stackoverflow.com/questions/30716354/how-do-i-do-a-literal-int64-in-go#30716481) for the techniques.)_ – icza Mar 15 '16 at 19:14
  • Sadly, but there is no way to do it in one line. – i.van Mar 16 '16 at 09:29

1 Answers1

11

You can ignore a return value using _ on the left hand side of assignment however, I don't think there is any way to do it while using the 'composite literal' initialization style you have in your example.

IE I can do returnValue1, _ := SomeFuncThatReturnsAresultAndAnError() but if you tried that in your example like;

ts := &student{
    name: td[0],
    ssn: td[2],
    next: students.next,
    age, _: strconv.Atoi(td[1]),
  }

It will also generate a compiler error.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115