Statements in if in golang

The Go programming language provides a way to execute conditional logic through the "if" statement. The syntax for the "if" statement in Go is as follows:

if condition { // Code block executed if the condition is true }

The "if" statement allows you to execute a block of code only if a certain condition is true. The condition is placed within the parentheses after the "if" keyword. If the condition evaluates to true, the code block within the curly braces will be executed. If the condition is false, the code block will be skipped.

Here's an example to illustrate the usage of the "if" statement in Go:

package main

import "fmt"

func main() {
   x := 10

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

In this example, we have a variable "x" initialized with a value of 10. The "if" statement checks if the value of "x" is greater than 5. Since 10 is indeed greater than 5, the code block within the curly braces is executed, and the message "x is greater than 5" is printed to the console.

You can also use the "else" statement along with the "if" statement to specify an alternative code block to be executed when the condition is false. Here's an example:

package main

import "fmt"

func main() {
   x := 3

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

In this example, the value of "x" is 3, which is not greater than 5. Therefore, the code block within the "else" statement is executed, and the message "x is less than or equal to 5" is printed to the console.

The "if" statement in Go can also be used with the "else if" statement to evaluate multiple conditions. Here's an example:

package main

import "fmt"

func main() {
   x := 7

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

In this example, the value of "x" is 7. The "if" statement checks if "x" is greater than 10, but it's not. Then, the "else if" statement checks if "x" is greater than 5, which is true. Therefore, the code block within the "else if" statement is executed, and the message "x is greater than 5 but less than or equal to 10" is printed to the console.