go中struct实现多个接口.type会显示哪个接口

package main

import (
	"fmt"
	"reflect"
)

type IntF1 interface {
	show1() string
}

type IntF2 interface {
	show2() string
}

type IntF3 interface {
	show3() string
}

type Cls struct {
	v1 string
	v2 string
	v3 string
}

func (c *Cls)show1() string {
	return c.v1
}

func (c *Cls)show2() string {
	return c.v2
}

func (c *Cls)show3() string {
	return c.v3
}

func Demo1(){
	var cls IntF2
	cls = &Cls{
		v1: "1",
		v2: "2",
		v3: "3",
	}
	icls := interface{}(cls)
	switch icls.(type) {
	case IntF2:
		fmt.Println("IntF2")
	case IntF1:
		fmt.Println("IntF1")
	case IntF3:
		fmt.Println("IntF3")
	default:
		fmt.Println(reflect.TypeOf(icls))
		
	}
}

func Demo2()  {
	var cls IntF1
	cls = &Cls{
		v1: "1",
		v2: "2",
		v3: "3",
	}
	icls := reflect.TypeOf(cls)

	switch icls.Kind() {
	case reflect.Interface:
		fmt.Println("Interface")
	case reflect.Struct:
		fmt.Println("Struct")
	default:
		fmt.Println(icls.Kind() )

	}
}

func main() {
	Demo1()
	Demo2()
}

结论,当一个struct实现多个interface的时候, 该struct转为interface再.type匹配类型的时候会以此查看哪一个case符合要求,有限匹配符合要求的case, 也就是说.(type)之后并不会确定该interface的类型,在它满足要求的所有case中,哪个写在前面就执行哪个case 而通过reflect.TypeOf().kind()得到的不是具体的用户实现的类型(用户实现的具体类型是无限的),而是reflect中包含的类型,是有限的,比如所有的结构体都属于reflect.struct, 接口都属于ptr。

发布了71 篇原创文章 · 获赞 27 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/github_34777264/article/details/102939140