If-Else

In Go an if looks like this:

  1. if x > 0 {
  2. return y
  3. } else {
  4. return x
  5. }

Since if and switch accept aninitialization statement, it’s common to see one used to set up a (local)variable.

  1. if err := SomeFunction(); err == nil {
  2. // do something
  3. } else {
  4. return err
  5. }

It is idomatic in Go to omit the else when the if statement’s body hasa break, continue, return or, goto, so the above code would be betterwritten as:

  1. if err := SomeFunction(); err != nil {
  2. return err
  3. }
  4. // do something

The opening brace on the first line must be positioned on the same line as theif statement. There is no arguing about this, because this is what gofmtoutputs.