写点什么

Go Switch - Go 中使用 Switch 的六种方式

用户头像
baiyutang
关注
发布于: 刚刚

译者:baiyutang

原文:https://dev.to/eternaldev/go-switch-6-ways-of-using-switch-in-go-5a0l


基本

Switch case is commonly used there are multiple condition checks to be done for a particular variable. It is easier to understand than having multiple if statements in your code. Switch statement evaluates the expression and executes the block of code that matches from the list of possible choices


package main
import "fmt"
func main() { status := 1
switch status { case 0: fmt.Println("Status - Todo")
case 1: fmt.Println("Status - In progress")
case 2: fmt.Println("Status - Done") }
}
复制代码


带有 default 语句

package main
import "fmt"
func main() { status := 1
switch status { case 0: fmt.Println("Status - Todo")
case 1: fmt.Println("Status - In progress")
case 2: fmt.Println("Status - Done")
default: fmt.Println("Not valid status") }
}
复制代码


package main
import "fmt"
func main() { status := 1
switch { case status == 0: fmt.Println("Status - Todo")
case status == 1: fmt.Println("Status - In progress")
case status == 2: fmt.Println("Status - Done")
default: fmt.Println("Status - Not valid") }
}
复制代码


case 列表

package main
import "fmt"
func main() { status := 4
switch status{ case 0: fmt.Println("Status - Todo")
case 1: fmt.Println("Status - In progress")
case 2, 3, 4: fmt.Println("Status - Done")
default: fmt.Println("Status - Not valid") }
}
复制代码


fallthrough 语句


package main
import "fmt"
func main() {
switch status := 3; { case status < 2: fmt.Println("Status is not done") case status < 4: fmt.Println("Status is done") fallthrough case status > 6: fmt.Println("Status is done but has some issues") }
}
复制代码


break 语句

package main
import "fmt"
func main() {
switch status := 2; { case status < 2: fmt.Println("Status is not done") case status < 4: fmt.Println("Status is done") if (status == 2) { break; } fallthrough case status > 6: fmt.Println("Status is done but has some issues") }
}
复制代码


发布于: 刚刚阅读数: 3
用户头像

baiyutang

关注

广州 2017.12.13 加入

Microservices | Golang | Cloud Nitive | “Smart work,Not hard”

评论

发布
暂无评论
Go Switch -  Go 中使用 Switch 的六种方式