1 Overview of Conditional Statements
Conditional statements are important tools for controlling the logical flow of programs in programming. In Golang, conditional statements are similar to those in other programming languages, but they have their own characteristics. They allow us to decide which code to execute based on the true or false conditions, greatly increasing the flexibility and maintainability of the code.
2 if Statement
2.1 Basic Usage of if Statement
The if
statement is the most basic conditional statement in the Go language. Its syntax is as follows:
if condition {
// Code to execute when the condition is true
}
Here’s a simple example:
package main
import "fmt"
func main() {
x := 10
if x > 5 {
fmt.Println("x is greater than 5")
}
}
This code will check if x
is greater than 5, and if it is, it will perform the print operation.
2.2 Conditional Expressions
Conditional expressions consist of comparison operators (such as ==
, !=
, <
, >
, <=
, >=
) and logical operators (such as &&
(AND), ||
(OR), !
(NOT)).
For example, to check if a variable is within a certain range:
y := 20
if y >= 10 && y <= 30 {
fmt.Println("y is between 10 and 30")
}
The above conditional expression uses the logical operator &&
to ensure that the value of y
is between 10 and 30.
2.3 if…else and else if Structure
When the if
condition is not met, we can use else
to execute an alternative code block. The else if
allows us to check multiple conditions. Here’s an example:
score := 88
if score >= 90 {
fmt.Println("Excellent")
} else if score >= 80 {
fmt.Println("Good")
} else if score >= 70 {
fmt.Println("Average")
} else {
fmt.Println("Below Average")
}
This code will print out different evaluations based on the value of score
.
3 switch Statement
3.1 Basic Syntax of switch
The switch
statement is a more concise conditional branch statement, especially suitable for situations where multiple values need to be evaluated. The basic syntax of the switch
statement is as follows:
switch expression {
case value1:
// Code to execute when matching value1
case value2:
// Code to execute when matching value2
default:
// Code to execute by default
}
If the value of expression
matches the value following case
, the respective code block will be executed.
3.2 switch Fallthrough
In Go’s switch
statement, each branch does not fall through to the next case by default unless the fallthrough
keyword is used.
switch num {
case 1:
fmt.Println("One")
fallthrough
case 2:
fmt.Println("Two")
default:
fmt.Println("Neither One nor Two")
}
In the above code, if num
is 1, even though it matches case 1
, due to the presence of the fallthrough
keyword, the program will continue to execute the code in case 2
and print “Two”.
3.3 Type Branching and Custom Branching
The switch
statement also supports branching based on variable types, known as type branching. Additionally, we can create more complex custom branching conditions.
Example of type branching:
var i interface{} = 1
switch i.(type) {
case int:
fmt.Println("i is an integer")
case float64:
fmt.Println("i is a float64")
default:
fmt.Println("i is another type")
}
Custom branching conditions can be written to perform more complex conditional judgments as needed.
4 Practical Exercise
In this section, we will deepen our understanding and application of conditional statements in Golang through specific examples. Through practical programming challenges, you will become more proficient in using if
and switch
statements to solve real-world problems.
Grade Calculator
Let’s write a simple grade calculator. This program will determine and output the corresponding grade based on the score entered by the user. The grading criteria are as follows:
- A for scores 90 and above
- B for scores between 80 and 89
- C for scores between 70 and 79
- D for scores between 60 and 69
- F for scores below 60
We can use either an if
statement or a switch
statement to implement this functionality. First, let’s look at an example using an if
statement:
package main
import (
"fmt"
)
func main() {
var score int
fmt.Print("Please enter the score: ")
fmt.Scan(&score)
if score >= 90 {
fmt.Println("Grade: A")
} else if score >= 80 {
fmt.Println("Grade: B")
} else if score >= 70 {
fmt.Println("Grade: C")
} else if score >= 60 {
fmt.Println("Grade: D")
} else {
fmt.Println("Grade: F")
}
}
In this code, we first declare a score
variable to store the user’s input score. We use the fmt.Scan
function to get the user’s input. Then, we use several if
and else if
statements to determine the corresponding grade for the score and use the fmt.Println
function to output the grade.
Next, let’s look at an example using a switch
statement:
package main
import (
"fmt"
)
func main() {
var score int
fmt.Print("Please enter the score: ")
fmt.Scan(&score)
switch {
case score >= 90:
fmt.Println("Grade: A")
case score >= 80:
fmt.Println("Grade: B")
case score >= 70:
fmt.Println("Grade: C")
case score >= 60:
fmt.Println("Grade: D")
default:
fmt.Println("Grade: F")
}
}
In the example using the switch
statement, the code structure is more concise and clear. We don’t need to use many consecutive if
and else if
statements; instead, we directly specify the conditions in each case
after the switch
. The score that does not match the condition of the previous case
will automatically move on to the next case
until it matches the corresponding conditional branch or reaches the default
case, which prints the F
grade.
Now that you have learned how to use if
and switch
for conditional judgments, try writing your own program and practicing to deepen your understanding.
In the next section, we will continue to introduce more practical problems to help you consolidate your mastery of conditional statements in Golang.
Please note that the above code is for instructional purposes. When used in practical applications, factors such as user interaction and error handling should be considered to make it more robust.