Golang 判断一个Type类型是否实现了某个接口

时间:2025-02-24 07:27:42

前言

    需求描述:判断任意一个func函数的第一个参数是否是一个。

    提到接口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  as its first parameter for testing
func FunctionAny(ctx , param ...interface{}) error {
	return nil
}

func main() {

	//Acquire the  of the function
	funcInput := (FunctionAny)

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

	//We can easily find the (u ) 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  is an interface, not a ,
	//we need to convert it to, or get a .

	//The easiest way is by using (interface{})
	actualContextType := new()

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

	var contextType = (actualContextType).Elem()

	((contextType)) //true
	((contextType))//false

}