Go - If Statement
If
The if
statement is used to execute a block of code if a certain condition is true
.
go
// The condition is an expression that evaluates to a boolean value.
if condition {
// Executed if the condition is `true`
}
Else
An optional else
clause can be used to execute code when the condition is false
.
go
if condition {
// Executed if the condition is `true`
} else {
// Executed if the condition is `false`
}
Else If
Multiple conditions may tested using else if
, the first condition that evaluates to true
its block will be executed.
go
n := 10
if n < 0 {
fmt.Println("n is a negative number")
} else if n > 0 {
fmt.Println("n is a positive number")
} else {
fmt.Println("n is zero")
}
Simple Statement
The if
statement can start with a short statement that is executed before the condition.
go
if n := getNumber(); n < 0 {
// The variables declared by the short statement
// are only available in the scope of the if statement.
} else {
// The variables are also available inside any of the `else` blocks.
}