Go基础系列:接口类型断言和type

您所在的位置:网站首页 Go类型推断 Go基础系列:接口类型断言和type

Go基础系列:接口类型断言和type

2024-02-06 05:55| 来源: 网络整理| 查看: 265

接口转回成具体类型

接口实例中可以存放各种实现了接口的类型实例,在有需要的时候,还可以通过ins.(Type)或ins.(*Type)的方式将接口实例ins直接转回Type类型的实例。

var i int = 30 var ins interface{} // 接口实例ins中保存的是int类型 ins = i x := ins.(int) // 接口转回int类型的实例i println(x) //输出30

但注意,这时候的i和x在底层不是同一个对象,它们的地址是不同的。

var i int = 30 var ins interface{} ins = i x := ins.(int) println("i addr: ",&i,"x addr: ",&x)

输出:

0xc042049f68 0xc042049f60

注意,接口实例转回时,接口实例中存放的是什么类型,才能转换成什么类型。同类型的值类型实例和指针类型实例不能互转,不同类型更不能互转。

在不能转换时,Golang将直接以Panic的方式终止程序。但可以处理转换失败时的panic,这时需要类型断言,也即类型检测。

接口类型探测:类型断言

类型探测的方式和类型转换的方式都是ins.(Type)和ins.(*Type)。当处于单个返回值上下文时,做的是类型转换,当处于两个返回值的上下文时,做的是类型探测。类型探测的第一个返回值是类型转换之后的类型实例,第二个返回值是布尔型的ok返回值。

// 如果ins保存的是值类型的Type,则输出 if t, ok := ins.(Type); ok { fmt.Printf("%T\n", v) } // 如果ins保存的是指针类型的*Type,则输出 if t, ok := ins.(*Type); ok { fmt.Printf("%T\n", v) } // 一个返回值的探测 t := ins.(Type) t := ins.(*Type)

以下是一个例子:

package main import "fmt" // Shaper 接口类型 type Shaper interface { Area() float64 } // Square struct类型 type Square struct { length float64 } // Square类型实现Shaper中的方法Area() func (s Square) Area() float64 { return s.length * s.length } func main() { var ins1, ins2 Shaper // 指针类型的实例 s1 := new(Square) s1.length = 3.0 ins1 = s1 if v, ok := ins1.(*Square); ok { fmt.Printf("ins1: %T\n", v) } // 值类型的实例 s2 := Square{4.0} ins2 = s2 if v, ok := ins2.(Square); ok { fmt.Printf("ins2: %T\n", v) } }

上面两个Printf都会输出,因为它们的类型判断都返回true。如果将ins2.(Square)改为ins2.(*Square),第二个Printf将不会输出,因为ins2它保存的是值类型的实例。

以下是输出结果:

ins1: *main.Square ins2: main.Square

特别需要注意的是,ins必须明确是接口实例。例如,以下前两种声明是有效的,第三种推断类型是错误的,因为它可能是接口实例,也可能是类型的实例副本。

var ins Shaper // 正确 ins := Shaper(s1) // 正确 ins := s1 // 错误

当ins不能确定是接口实例时,用它来进行测试,例如ins.(Square)将会报错:

invalid type assertion:ins.(Square) (non-interface type (type of ins) on left)

它说明了左边的ins是非接口类型(non-interface type)。

另一方面,通过接口类型断言(ins.(Type)),如果Type是一个接口类型,就可以判断接口实例ins中所保存的类型是否也实现了Type接口。例如:

var r io.Read tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0) if err != nil { return nil, err } r = tty var w io.Writer w = r.(io.Writer)

上面的r是io.Read接口的一个实例变量,它里面保存的是tty和它的类型,即(tty, *os.File),然后断言r的类型,探测它里面的类型*File是否也实现了io.Writer接口,如果实现了,则保存到io.Writer接口的实例变量w中,这样w实例也将保存(tty,*os.File)。

由于任意内容都实现了空接口,所以,总是可以把一个接口实例无需通过任何断言地赋值给一个空接口实例:

var empty interface{} empty = w

现在empty也保存了(tty,*os.File)。

type Switch结构

直接用if v,ok := ins.(Type);ok {}的方式做类型探测在探测类型数量多时不是很方便,需要重复写if结构。

Golang提供了switch...case结构用于做多种类型的探测,所以这种结构也称为type-switch。这是比较方便的语法,比如可以判断某接口如果是A类型,就执行A类型里的特有方法,如果是B类型,就执行B类型里的特有方法。

用法如下:

switch v := ins.(type) { case *Square: fmt.Printf("Type Square %T\n", v) case *Circle: fmt.Printf("Type Circle %T\n", v) case nil: fmt.Println("nil value: nothing to check?") default: fmt.Printf("Unexpected type %T", v) }

其中ins.(type)中的小写type是固定的词语。

以下是一个使用示例:

package main import ( "fmt" ) // Shaper 接口类型 type Shaper interface { Area() float64 } // Circle struct类型 type Circle struct { radius float64 } // Circle类型实现Shaper中的方法Area() func (c *Circle) Area() float64 { return 3.14 * c.radius * c.radius } // Square struct类型 type Square struct { length float64 } // Square类型实现Shaper中的方法Area() func (s Square) Area() float64 { return s.length * s.length } func main() { s1 := &Square{3.3} whichType(s1) s2 := Square{3.4} whichType(s2) c1 := new(Circle) c1.radius = 2.3 whichType(c1) } func whichType(n Shaper) { switch v := n.(type) { case *Square: fmt.Printf("Type Square %T\n", v) case Square: fmt.Printf("Type Square %T\n", v) case *Circle: fmt.Printf("Type Circle %T\n", v) case nil: fmt.Println("nil value: nothing to check?") default: fmt.Printf("Unexpected type %T", v) } }

上面的type-switch中,之所以没有加上case Circle,是因为Circle只实现了指针类型的receiver,根据Method Set对接口的实现规则,只有指针类型的Circle示例才算是实现了接口Shaper,所以将值类型的示例case Circle放进type-switch是错误的。

作者:骏马金龙 出处:http://www.cnblogs.com/f-ck-need-u/ Linux运维交流群:921383787

Linux系列文章:https://www.cnblogs.com/f-ck-need-u/p/7048359.html Shell系列文章:https://www.cnblogs.com/f-ck-need-u/p/7048359.html 网站架构系列文章:http://www.cnblogs.com/f-ck-need-u/p/7576137.html MySQL/MariaDB系列文章:https://www.cnblogs.com/f-ck-need-u/p/7586194.html Perl系列:https://www.cnblogs.com/f-ck-need-u/p/9512185.html Go系列:https://www.cnblogs.com/f-ck-need-u/p/9832538.html Python系列:https://www.cnblogs.com/f-ck-need-u/p/9832640.html Ruby系列:https://www.cnblogs.com/f-ck-need-u/p/10805545.html 操作系统系列:https://www.cnblogs.com/f-ck-need-u/p/10481466.html 精通awk系列:https://www.cnblogs.com/f-ck-need-u/p/12688355.html



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3