登录
首页 >  Golang >  Go问答

验证方法类型是否与函数类型一致

来源:stackoverflow

时间:2024-03-23 09:12:31 430浏览 收藏

在 Go 语言中,可以通过反射机制验证方法是否与函数类型一致。其中,一种方法是使用 `reflect.Value.Type().ConvertibleTo`,该方法可以检查一个类型是否可以转换为另一个类型。另一种方法是分别检查输入和输出类型,确保方法的输入类型和函数的输入类型一致,方法的输出类型和函数的输出类型一致。

问题内容

给定以下示例,如何检查方法是否与函数签名匹配?

package main

import (
    "fmt"
    "context"
    "reflect"
)

// signature to check
type Fn func(context.Context)

type testStruct struct {}

func (*testStruct) DoSomething(context.Context){}
func (*testStruct) DoSomethingElse([]byte){}


func main() {
    structType := reflect.TypeOf(&testStruct{})
    for i := 0; i < structType.NumMethod(); i++ {
        fmt.Println("======================")
        method := structType.Method(i)
        fmt.Println(method.Name)
        fmt.Println(method.Type.String())

        // compare method and Fn signature
    }
}

https://play.golang.org/p/ridfp0e14ge


解决方案


1。使用 reflect.value.type().convertibleto

注意 reflect.valueof 插入 reflect.typeof

package main

import (
    "context"
    "fmt"
    "reflect"
)

type fn func(context.context)

type teststruct struct{}

func (*teststruct) dosomething(context.context)           {}
func (*teststruct) dosomethingelse([]byte)                {}
func (*teststruct) dosomethingelse2(context.context) error { return nil }

func main() {
    structtype := reflect.valueof(&teststruct{})
    for i := 0; i < structtype.nummethod(); i++ {
        fmt.println("======================")
        method := structtype.method(i)

        // compare method and fn
        if method.type().convertibleto(reflect.typeof((fn)(nil))) {
            fmt.println("function of correct type")
        }
    }
}

https://play.golang.org/p/A9_bpURinad

2。分别检查输入和输出

package main

import (
    "context"
    "fmt"
    "reflect"
)

type Fn func(context.Context)

type testStruct struct{}

func (*testStruct) DoSomething(context.Context) {}
func (*testStruct) DoSomethingElse([]byte)      {}

func main() {
    structType := reflect.TypeOf(&testStruct{})
    rctx := reflect.TypeOf(new(context.Context)).Elem()
    for i := 0; i < structType.NumMethod(); i++ {
        fmt.Println("======================")
        method := structType.Method(i)
        fmt.Println(method.Name)
        fmt.Println(method.Type.String())

        if method.Type.NumIn() != 2 {
            fmt.Println("wrong number of inputs, expected 1")
            continue
        }

        if method.Type.In(1) != rctx {
            fmt.Println("input of wrong type, expected context.Context")
            continue
        }

        if method.Type.NumOut() != 0 {
            fmt.Println("wrong number of outputs, expected 0")
            continue
        }

        fmt.Printf("%v is a function of correct type\n", method.Name)
    }
}

https://play.golang.org/p/YDsJ9MSiumF

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>