Search code examples
goconditional-statementsshort-circuiting

Checking Dictionary Key Existence in Golang on right side of boolean condition


I have an array of maps in golang, I'm iterating over the list and need to check if a key from the current iteration exists in the next map in the list, I know the normal way to check if an element exists in a map is to do:

if _, ok := m[key]; ok {
  ...
}

but is there a way to do this?

if index < len(arr)-1 && (_, ok := arr[index+1][key]; ok) {
  ...
}

where short-circuiting would work and the code remains in one line?


Solution

  • AFAIK, there is no way to do it in one line.

    Hey, Go even does not have the ?: operator:

    The reason ?: is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. The if-else form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.

    And one of Go's proverbs is Clear is better than clever.

    So don't struggle with it. Just write it like this:

    if index < len(arr)-1 {
        if _, ok := arr[index+1][key]; ok {
            //...
        }
    }
    

    Regarding you're iterating over the list, maybe it's better to write it like this:

    // assumes arr has at least 1 items
    for index := range arr[0 : len(arr)-1] {
        if _, ok := arr[index+1][key]; ok {
            //...
        }
    }