If-Else
In Go an if
looks like this:
if x > 0 {
return y
} else {
return x
}
Since if
and switch
accept aninitialization statement, it’s common to see one used to set up a (local)variable.
if err := SomeFunction(); err == nil {
// do something
} else {
return err
}
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:
if err := SomeFunction(); err != nil {
return err
}
// 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 gofmt
outputs.
当前内容版权归 Miek Gieben 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 Miek Gieben .