Golang 判斷一個Type類型是否實現了某個接口

前言

    需求描述:判斷任意一個func函數的第一個參數是否是一個context.Context。

    提到接口interface{],想必大家用的最多的是無非是這兩種情景:

        1、給struct實現接口;

        2、萬能數據類型+類型斷言。

    針對第二點,我們的使用情況通常是類型斷言,通俗的說是,判斷 這個未知interface是不是那種實際類型。

asserted, ok := someTypeInInterface.(CertainTargetType)

  那麼我們能不能反過來,知道這個具體Type是否實現了那個接口?

   答案是肯定的。網上搜了一下,貌似找不到,唯一接近我的問題的,可解決方案居然是依賴IDE和編譯器報錯???我翻了一下reflect包,發現了居然有一個Implements函數接口方法。。。試了一下,達成目標。具體使用和測試過程如下。

Start

package main

import (
	"context"
	"log"
	"reflect"
)

//Define a function that requires a context.Context as its first parameter for testing
func FunctionAny(ctx context.Context, param ...interface{}) error {
	return nil
}

func main() {

	//Acquire the reflect.Type of the function
	funcInput := reflect.ValueOf(FunctionAny)

	//This is how we get the reflect.Type of a parameter of a function
	//by index of course.
	firstParam := funcInput.Type().In(0)
	secondParam := funcInput.Type().In(1)

	//We can easily find the reflect.Type.Implements(u reflect.Type) func if we look into the source code.
	//And it says "Implements reports whether the type implements the interface type u."
	//This looks like what we want, no, this is exactly what we want.
	//To use this func, a Type param is required. Because context.Context is an interface, not a reflect.Type,
	//we need to convert it to, or get a reflect.Type.

	//The easiest way is by using reflect.TypeOf(interface{})
	actualContextType := new(context.Context)

	//Another syntax is :
	//actualContextType := (*context.Context)(nil)
	//We know that nil is the zero value of reference types, simply conversion is OK.

	var contextType = reflect.TypeOf(actualContextType).Elem()

	log.Println(firstParam.Implements(contextType)) //true
	log.Println(secondParam.Implements(contextType))//false

}

 

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