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。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章