Conditional statements in Go allow you to execute different code blocks based on specific conditions. The most common conditional statement is the if
statement.
if Statement
The if
statement evaluates a condition and executes a block of code if the condition is true. Here’s the basic syntax:
Go
if condition {
// Code to execute if the condition is true
}
Example:
Go
name := "Alice"
if name == "Alice" {
fmt.Println("Hello, Alice!")
}
if-else Statement
You can use the if-else
statement to execute different code blocks based on whether the condition is true or false:
Go
if condition {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Example:
Go
age := 18
if age >= 18 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are a minor.")
}
if-else if-else Statement
For more complex conditions, you can use nested if-else
statements or the if-else if-else
statement:
Go
if condition1 {
// Code to execute if condition1 is true
} else if condition2 {
// Code to execute if condition1 is false and condition2 is true
} else {
// Code to execute if both condition1 and condition2 are false
}
Loops
Loops in Go allow you to repeatedly execute a block of code until a certain condition is met. Go provides three types of loops: for
, for range
, and while
.
for Loop
The for
loop is the most common loop in Go. It has three parts: initialization, condition, and post-statement.
Go
for initialization; condition; post-statement {
// Code to execute in the loop
}
Example:
Go
for i := 0; i < 5; i++ {
fmt.Println(i)
}
for range Loop
The for range
loop is used to iterate over elements in a collection, such as arrays, slices, maps, and channels.
Go
for key, value := range collection {
// Code to execute for each element
}
Example:
Go
fruits := []string{"apple", "banana", "orange"}
for index, fruit := range fruits {
fmt.Println(index, fruit)
}
while Loop
The while
loop is an alternative to the for
loop. It continues to execute as long as a condition is true.
Go
for condition {
// Code to execute in the loop
}
Example:
Go
count := 0
for count < 10 {
fmt.Println(count)
count++
}
Using Conditionals and Loops in gRPC
Conditional statements and loops can be used in gRPC services to implement various logic. For example, you might use a for
loop to iterate over a list of items, or an if
statement to check if a user is authorized to perform an action.