# 07.4.2 Switch用于类型判断

在本小节中，将在Go代码`switch.go`中讲解如何使用`switch`语句来区分不同的数据类型，这将分为四个部分进行介绍。`switch.go`的Go代码部分基于`useInterface.go`，但它将添加另一个名为`rectangle`的类型，不需要实现任何接口的方法。

````
>```go
> package main
>
> import (
>     "fmt"
> )
>
````

由于`switch.go`中的代码不需要实现`myInterface.go`中定义的接口，因此不需要导入`myInterface`包。

````
>```go
> type square struct {
>     X float64
> }
>
> type circle struct {
>     R float64
> }
>
> type rectangle struct {
>     X float64
>     Y float64
> }
>
````

这三种类型都很简单。

````
>```go
> func tellInterface(x interface{}) {
>     switch v := x.(type) {
>     case square:
>         fmt.Println("This is a square!")
>     case circle:
>         fmt.Printf("%v is a circle!\n", v)
>     case rectangle:
>         fmt.Println("This is a rectangle!")
>     default:
>         fmt.Printf("Unknown type %T!\n", v)
>     }
> }
>
````

在这里，实现了一个名为`tellInterface()`的函数，该函数有一个类型为`interface`的参数`x`。

这个函数实现体现了区分不同数据类型的`x`参数。通过使用返回`x`元素类型的`x.(type)`语句来实现这样的效果。在`fmt.Printf()`函数中使用的格式化字符串`%v`来获取类型的值。

````
>```go
> func main() {
>     x := circle{R: 10}
>     tellInterface(x)
>     y := rectangle{X: 4, Y: 1}
>     tellInterface(y)
>     z := square{X: 4}
>     tellInterface(z)
>     tellInterface(10)
> }
>
````

执行`switch.go`将生成以下的输出：

> ```
> $ go run switch.go
> {10} is a circle!
> This is a rectangle!
> This is a square!
> Unknown type int!
> ```


---

# 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/7-fan-she-he-jie-kou/07.4/07.4.2.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.
