golang中接口对象的转型

接口对象的转型有两种方式:

1. 方式一:instance,ok:=接口对象.(实际类型)

  如果该接口对象是对应的实际类型,那么instance就是转型之后对象,ok的值为true
  配合if...else if...使用

2. 方式二:

  接口对象.(type)
  配合switch...case语句使用

示例:

package main

import (
	"fmt"
	"math"
)

type shape interface {
	perimeter() int
	area() 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)
}

  

posted @ 2021-10-11 15:02  专职  阅读(110)  评论(0编辑  收藏  举报