教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Golang 判断一个Type类型是否实现了某个接口

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

发布时间:2022-12-12   编辑:jiaochengji.com
教程集为您提供Golang 判断一个Type类型是否实现了某个接口等资源,欢迎您收藏本站,我们将为您提供最新的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

}

 

到此这篇关于“Golang 判断一个Type类型是否实现了某个接口”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
【Golang】go语言面向接口
go 判断类是否实现了指定接口
goLang 类型断言 type assertion
一看就懂系列之Golang的接口
Go语言基础之接口(面向对象编程下)
如何判断Golang接口是否实现?
Go语言接口interface
go语言接口断言的使用
Golang interface 接口要点梳理
Go语言_接口查询

[关闭]
~ ~