Conditional Statements in Go
Conditional Statements
1
Conditional statements in Go are used to execute a certain block of code based on a specific condition. There are two main types of conditional statements in Go: if-else
and switch
.
The if-else
statement is used to execute a block of code if a certain condition is true and another block of code if the condition is false.
Example:
if x > 10 { fmt.Println("x is greater than 10") } else { fmt.Println("x is less than or equal to 10") }
The switch
statement is used to execute a block of code depending on the value of an expression. The case
statements represent different possible values of the expression, and the default
statement is executed if none of the case statements match the expression.
Example:
switch day { case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") case 3: fmt.Println("Wednesday") case 4: fmt.Println("Thursday") case 5: fmt.Println("Friday") case 6: fmt.Println("Saturday") case 7: fmt.Println("Sunday") default: fmt.Println("Invalid day") }
It is important to note that in Go, the condition in an if
or switch
statement must always be a Boolean expression, which is an expression that evaluates to true or false.
Overall, conditional statements are an essential part of programming in Go, allowing developers to control the flow of their code and make it more efficient and effective.
March 27, 2023