go

Clean way to break from an if statement in Go


I have the following case:

if condition {
  if nestedCondition {
    // logic
    // I want to somehow break at this point but also be able
    // to check the outer otherCondition
  }
  if otherNestedCondition {
    // logic
  }
}
if otherCondition {
  //logic
}

Is there a way to "break" from nestedCondition but also be able to check otherCondition?


Solution

  • break statements only break from for, switch or select. There is no break statement to break from an if or from an arbitrary block. If possible, restructure and rearrange your conditions so you don't end up in a situation where you'd want to break from an if.

    What you may also do is use a function (either anonymous or named one), and return from it when you would want to "break":

    if condition {
        func() {
            if nestedCondition {
                // To break:
                return
            }
            if otherNestedCondition {
                // logic
            }
        }()
    }
    if otherCondition {
        //logic
    }
    

    Yet another solution would be to use goto and labeled statements:

        if condition {
            if nestedCondition {
                // To break:
                goto outside
            }
            if otherNestedCondition {
                // logic
            }
        }
    outside:
        if otherCondition {
            //logic
        }
    

    Although note that using goto is extremely rare in Go (and in most languages), and should not be "overused" (or used at all).