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!

results matching ""

    No results matching ""