/

Conditionals in Go - A Guide to Using If and Switch Statements

Conditionals in Go - A Guide to Using If and Switch Statements

In Go, conditionals are used to execute different instructions based on certain conditions. The primary conditional statement is the if statement, which allows you to perform actions when a condition is true.

1
2
3
if age < 18 {
// Do something if the age is less than 18 (underage)
}

The else part of the if statement is optional and can be used to specify what to do when the condition is false.

1
2
3
4
5
if age < 18 {
// Do something if the age is less than 18 (underage)
} else {
// Do something if the age is 18 or older (adult)
}

Multiple if statements can be combined using the else if clause to handle multiple conditions.

1
2
3
4
5
6
7
if age < 12 {
// Do something specific for children
} else if age < 18 {
// Do something specific for teenagers
} else {
// Do something for adults
}

If you define a variable inside an if statement, it is only visible within that block. The same applies to else statements and any other block created with {}.

If you have many different if statements to check a single condition, it is often more efficient to use the switch statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
switch age {
case 0:
fmt.Println("Zero years old")
case 1:
fmt.Println("One year old")
case 2:
fmt.Println("Two years old")
case 3:
fmt.Println("Three years old")
case 4:
fmt.Println("Four years old")
default:
fmt.Println(i + " years old")
}

Unlike in C, JavaScript, and some other languages, you do not need to include a break statement after each case in Go.

By using conditionals effectively, you can write more organized and readable code in Go. Consider the specific situations and requirements of your program when deciding whether to use if statements or switch statements.

tags: [“Go”, “conditionals”, “if statement”, “switch statement”, “programming”]