📜  在 Golang 中组合条件语句(1)

📅  最后修改于: 2023-12-03 14:50:55.874000             🧑  作者: Mango

在 Golang 中组合条件语句

在 Golang 的程序中,我们经常需要根据某些条件来执行不同的代码块。组合条件语句可以帮助我们更好地实现这个目的。

if...else 语句

在 Golang 中,我们可以使用 if...else 语句来实现基本的条件判断。

if condition {
    // if condition is true, execute this code block
} else {
    // if condition is false, execute this code block
}

例如:

age := 18

if age >= 18 {
    fmt.Println("You are an adult.")
} else {
    fmt.Println("You are not an adult yet.")
}

在上面的例子中,如果 age 变量的值大于或等于 18,则打印 "You are an adult."。否则,打印 "You are not an adult yet."。

我们也可以结合多个条件进行判断:

if condition1 {
    // if condition1 is true, execute this code block
} else if condition2 {
    // if condition1 is false and condition2 is true, execute this code block
} else {
    // if condition1 and condition2 are false, execute this code block
}

例如:

age := 18

if age < 6 {
    fmt.Println("You are a kid.")
} else if age >= 6 && age < 18 {
    fmt.Println("You are a teenager.")
} else {
    fmt.Println("You are an adult.")
}

在上面的例子中,如果 age 变量的值小于 6,则打印 "You are a kid."。如果 age 变量的值大于等于 6 且小于 18,则打印 "You are a teenager."。否则,打印 "You are an adult."。

switch...case 语句

除了 if...else 语句,我们也可以使用 switch...case 语句来实现条件判断。

switch expression {
case value1:
    // if expression equals value1, execute this code block
case value2:
    // if expression equals value2, execute this code block
default:
    // if expression does not equal value1 or value2, execute this code block
}

例如:

dayOfWeek := "Saturday"

switch dayOfWeek {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
    fmt.Println("It's a weekday.")
case "Saturday", "Sunday":
    fmt.Println("It's a weekend.")
default:
    fmt.Println("Invalid day of week.")
}

在上面的例子中,如果 dayOfWeek 变量的值等于 "Monday"、"Tuesday"、"Wednesday"、"Thursday" 或 "Friday",则打印 "It's a weekday."。如果 dayOfWeek 变量的值等于 "Saturday" 或 "Sunday",则打印 "It's a weekend."。否则,打印 "Invalid day of week."。

带有初始化语句的条件语句

我们也可以在 if 和 switch 语句中包含初始化语句。

if initialization; condition {
    // if condition is true, execute this code block
}

switch initialization; expression {
case value1:
    // if expression equals value1, execute this code block
case value2:
    // if expression equals value2, execute this code block
default:
    // if expression does not equal value1 or value2, execute this code block
}

例如:

if age := 18; age >= 18 {
    fmt.Println("You are an adult.")
}

switch dayOfWeek := "Saturday"; dayOfWeek {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
    fmt.Println("It's a weekday.")
case "Saturday", "Sunday":
    fmt.Println("It's a weekend.")
default:
    fmt.Println("Invalid day of week.")
}

在上面的例子中,age 变量的值被初始化为 18,然后判断它是否大于等于 18。如果是,打印 "You are an adult."。dayOfWeek 变量的值被初始化为 "Saturday",然后根据其值执行相应的代码块。