golang中接口对象的转型两种方式

接口对象的转型有两种方式:
1. 方式一:instance,ok:=接口对象.(实际类型)
如果该接口对象是对应的实际类型,那么instance就是转型之后对象,ok的值为true
配合if...else if...使用
2. 方式二:
接口对象.(type)
配合switch...case语句使用
示例:

package main import ("fmt""math") type shape interface {perimeter() intarea() int} type rectangle struct {a int// 长b int// 宽}func (r rectangle) perimeter() int {return (r.a + r.b) * 2}func (r rectangle) area() int {return r.a * r.b} type circle struct {radios int}func (c circle) perimeter() int {return 2 * c.radios * int(math.Round(math.Pi))}func (c circle) area() int {return int(math.Round(math.Pow(float64(c.radios), 2) * math.Pi))} func getType(s shape) {if i, ok := s.(rectangle); ok {fmt.Printf("长方形的长:%d,长方形的宽是:%d\n", i.a, i.b)} else if i, ok := s.(circle); ok {fmt.Printf("圆形的半径是:%d\n", i.radios)}} func getType2(s shape) {switch i := s.(type) {case rectangle:fmt.Printf("长方形的长:%d,长方形的宽是:%d\n", i.a, i.b)case circle:fmt.Printf("圆形的半径是:%d\n", i.radios)}} func getResult(s shape) {fmt.Printf("图形的周长是:%d,图形的面积是:%d\n", s.perimeter(), s.area())} func main() {r := rectangle{a: 10, b: 20}getType(r)getResult(r) c := circle{radios: 5}getType2(c)getResult(c)}

上面的例子使用的是方式一,如果要使用方式2,可以将getType()函数改为:
func getType(s shape) { switch i := s.(type) { case rectangle:fmt.Printf("图形的长:%.2f,图形的宽:%.2f \n", i.a, i.b) case triangle:fmt.Printf("图形的第一个边:%.2f,图形的第二个边:%.2f,图形的第三个边:%.2f \n",i.a,i.b,i.c) case circular:fmt.Printf("图形的半径:%.2f \n",i.radius) }}

PS:上面求三角形面积使用了海伦公式求三角形的面积,公式为:
三角形的面积=平方根[三角形周长的一半×(三角形周长的一半减去第一个边)×(三角形周长的一半减去第二个边)×(三角形周长的一半减去第三个边)]
【golang中接口对象的转型两种方式】到此这篇关于golang中接口对象的转型的文章就介绍到这了,更多相关golang接口对象内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读