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
> }
>

这三种类型都很简单。

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

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

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

Last updated

Was this helpful?