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

}

 

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