# 04.6 switch语句

在本节介绍`switch`语句主要是因为`switch`可以用于正则表达式！首先看一段`switch`代码块：

> ```go
> switch asString {
>     case "1":
>         fmt.Println("One")
>     case "0":
>         fmt.Println("Zero")
>     default:
>         fmt.Println("Do not care!")
> }
> ```

这段代码能够区分不同的`asString`值所对应的不同操作。

> *`switch`代码块设置default子句是非常棒的实践。由于`switch`的`case`语句是依赖顺序的，所以`default`子句总是在最后声明。*

`switch`的使用还可以更加灵活：

> switch {
>
> case number < 0:
>
> ​ fmt.Println("Less than zero")
>
> case number > 0:
>
> ​ fmt.Println("Bigger than zero")
>
> default:
>
> ​ fmt.Println("zero")
>
> }

上面的代码块能够在某个数字正数、负数、以及0的情况下执行不同的任务。如你所见，`switch`的分支语句可以是条件语句，那么其分支语句同样也可以是正则表达式！

关于`switch`的用法将在`switch.go`中分5部分展示。

第一部分：

> ```go
> package main
>
> import (
>     "fmt"
>     "os"
>     "regexp"
>     "strconv"
> )
>
> func main() {
>     arguments := os.Args
>     if len(arguments) <2 {
>         fmt.Println("Usage: switch number")
>         os.Exit(1)
>     }
> ```

`regex`包用于生成正则表达。

第二部分代码：

> ```go
> number, err := strconv.Atoi(arguments[1])
>     if err != nil {
>         fmt.Println("The value is not an integer",number)
>     }else {
>         switch {
>         case number<0:
>             fmt.Println("Less than zero")
>         case number >0:
>             fmt.Println("Bigger than zero")
>         default:
>             fmt.Println("Zero")
>         }
>     }
> ```

第三部分代码：

> ```go
> asString := arguments[1]
>     switch  asString{
>     case "5":
>         fmt.Println("Five")
>     case "0":
>         fmt.Println("Zero")
>     default:
>         fmt.Println("Do not care")
>     }
> ```

这部分代码说明case`子句可以包含硬编码的变量，这种情况通常是`switch\`后跟有一个变量。

第四部分代码：

> ```go
> var negative = regexp.MustCompile(`-`)
>     var floatingPoint = regexp.MustCompile(`\d?\.\d`)
>     var mail = regexp.MustCompile(`^[^@]+@[^@.]+\.[^@.]+`)
>     switch {
>     case negative.MatchString(asString):
>         fmt.Println("Negative number")
>     case floatingPoint.MatchString(asString):
>         fmt.Println("Floating Point")
>     case mail.MatchString(asString):
>         fmt.Println("It is an email")
>         fallthrough
>     default:
>         fmt.Println("Something else")
>     }
> ```

这部分代码十分有趣。首先，我们定义了3个正则表达`negative`,`floatingPoint`,以及`mail`。然后使用`regexp.MatchString()`在`switch`中匹配不同的情况。

最后，`fallthrough`关键字告诉Go执行接下来的分支，即`default`分支。这意味着无论`mail.MatchString(asString)`是否成功匹配，`default`子句都会执行。

最后一部分：

> ```go
> var aType error = nil
>     switch aType.(type) {
>     case nil:
>         fmt.Println("It is a nil interface")
>     default:
>         fmt.Println("It it not a nil interface")
>
>     }
>
> }
> ```

这段代码说明`switch`能够区分不同类型，你将在第7章中了解到接口的知识。执行`switch.go`将会产生如下输出：

> ```
> $ go run switch.go
> Usage: switch number
> exit status 1
> hanshanjiedeMacBook-Pro:chapter4 hanshanjie$ go run switch.go mike@g.com
> The value is not an integer 0
> Do not care
> It is an email
> Something else
> It is a nil interface
> hanshanjiedeMacBook-Pro:chapter4 hanshanjie$ go run switch.go 5
> Bigger than zero
> Five
> Something else
> It is a nil interface
> hanshanjiedeMacBook-Pro:chapter4 hanshanjie$ go run switch.go 0
> Zero
> Zero
> Something else
> It is a nil interface
> hanshanjiedeMacBook-Pro:chapter4 hanshanjie$ go run switch.go 1.2
> The value is not an integer 0
> Do not care
> Floating Point
> It is a nil interface
> hanshanjiedeMacBook-Pro:chapter4 hanshanjie$ go run switch.go -1.5
> The value is not an integer 0
> Do not care
> Negative number
> It is a nil interface
> ```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wskdsgcf.gitbook.io/mastering-go-zh-cn/04.0/04.6.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
