1

This tests if a map contains a certain value:

_, ok := myMap["foo"]

Is there a way to use this check in an if statement, so that I can chain multiple tests together?

if ("foo" in map1) || ("bar" in map2) {
// do stuff
}
Jan Groth
  • 14,039
  • 5
  • 40
  • 55

1 Answers1

1

This should be roughly what you're looking for.

if _, ok := myMap["foo"]; ok {
    //do stuff
}

You should be able to chain multiple statements in the parentheses so that you can have multiple checks at a time.

if (_, okfoo := myMap["foo"]; _, okbar := myMap["bar"]; okfoo || okbar) {
    // do stuff
}

Graytr
  • 104
  • 8
  • Only that it looks horrible... ;-) I was hoping for a single expression (per map) that checks the return value directly and saves the assignment altogether. Thanks for answering anyways! – Jan Groth Mar 16 '17 at 04:49
  • I completely agree that is looks horrible. Sorry about that. – Graytr Mar 16 '17 at 04:54
  • Perhaps something along the lines of (myMap["foo"])[1] would work? – Graytr Mar 16 '17 at 04:55
  • 1
    I don't believe `(_, ok := myMap["foo"]; ok == true)` is valid syntax; You need to get rid of the parenthesis, or better yet, do `_, ok := myMap["foo"]; ok`. – Akavall Mar 16 '17 at 04:59
  • 1
    Also the 2nd snippet still won't work : ["Only one 'simple statement' is permitted at the beginning of an if-statement"](http://stackoverflow.com/a/25284952/2998271) – har07 Mar 16 '17 at 05:00
  • @Akavall, \@har07, Sorry about that, I was unaware only one statement was allowed. Thank you for correcting me. – Graytr Mar 16 '17 at 05:05