Conditions

Conditions in Go

Go, like many other programming languages, allows us to make decisions in our code by using conditions. In Go, we use the if statement to evaluate conditions.

If Statement

The basic syntax of an if statement is as follows:

if condition {
  // code to be executed if the condition is true
}

For example:

if x > 10 {
  fmt.Println("x is greater than 10")
}

If...Else Statement

The if statement can be extended with an else clause, which is executed if the condition is false:

if condition {
  // code to be executed if the condition is true
} else {
  // code to be executed if the condition is false
}

For example:

if x > 10 {
  fmt.Println("x is greater than 10")
} else {
  fmt.Println("x is less than or equal to 10")
}

If...Else If...Else Statement

The if statement can be extended with multiple else if clauses to check multiple conditions:

if condition1 {
  // code to be executed if condition1 is true
} else if condition2 {
  // code to be executed if condition1 is false and condition2 is true
} ...
else if conditionN {
  // code to be executed if all previous conditions are false and conditionN is true
} else {
  // code to be executed if all conditions are false
}

For example:

if x > 10 {
  fmt.Println("x is greater than 10")
} else if x < 0 {
  fmt.Println("x is less than 0")
} else {
  fmt.Println("x is between 0 and 10")
}

Short If Statement

Go also provides a short form of the if statement, which allows us to declare a local variable and execute a statement based on a condition. The syntax is as follows:

if condition {
  // code to be executed if the condition is true
}

For example:

if x := 42; x == 42 {
  fmt.Println("x is equal to 42")
}

In this example, x is declared and assigned the value of 42 within the if statement. The if statement checks if x is equal to 42 and executes the associated code if the condition is true. Note that the scope of x is limited to the if statement.

Last updated