gpt4 book ai didi

go - 在 Go 中,如何检查接口(interface)是否实现了结构的所有导出方法?

转载 作者:行者123 更新时间:2023-12-01 22:34:53 28 4
gpt4 key购买 nike

我正在开发一个使用 interfacer 的 Go 库。工具 ( https://github.com/rjeczalik/interfaces ) 从结构创建接口(interface),然后运行 ​​moq ( https://github.com/matryer/moq ) 为该接口(interface)生成一个模拟对象。现在我想编写一个单元测试,如果有人在没有更新接口(interface)和模拟的情况下将导出的方法添加到结构中,该测试将失败。

在高层次上,在我看来,我可以获得 reflect.Value接口(interface)和结构并调用NumMethod()在每个上,然后检查数字是否相等。然而,我正在努力实现这个想法。

例如,如果我尝试这个:

package main

import (
"fmt"
"reflect"
)

type PersonInterface interface {
GetName() string
}

type Person struct {
Name string
}

func (person *Person) GetName() string {
return person.Name
}

func main() {
person := Person{}
v := reflect.ValueOf(&person)
fmt.Println(v.NumMethod())

var personInterface PersonInterface
w := reflect.ValueOf(personInterface)
fmt.Println(w.NumMethod())
}

我可以调用获取 person 的方法数,但不属于 personInterface ,因为这会出现错误消息

reflect: call of reflect.Value.NumMethod on zero Value



这是完整的错误:
> go run assert_struct.go
1
panic: reflect: call of reflect.Value.NumMethod on zero Value

goroutine 1 [running]:
reflect.Value.NumMethod(0x0, 0x0, 0x0, 0x1)
/usr/local/Cellar/go@1.12/1.12.12/libexec/src/reflect/value.go:1262 +0xc1
main.main()
/Users/kurt/Documents/Scratch/assert_struct.go:27 +0x1a5
exit status 2

我怎样才能得到 interface 实现的方法的数量? ,更一般地说,我将如何检查接口(interface)是否实现了结构的所有导出方法?

最佳答案

转换 mkopriva对答案的 Go Playground 评论,reflect.ValueOf()需要在指向接口(interface)的指针( PersonInterface )上调用,然后是 Elem()需要调用它:

package main

import (
"fmt"
"reflect"
)

type PersonInterface interface {
GetName() string
}

type Person struct {
Name string
}

func (person *Person) GetName() string {
return person.Name
}

func main() {
person := Person{}
v := reflect.ValueOf(&person)
fmt.Println(v.NumMethod())

var personInterface PersonInterface
w := reflect.ValueOf(&personInterface)
fmt.Println(w.Elem().NumMethod())
}

这实际上类似于“反射的三定律”博客 ( https://blog.golang.org/laws-of-reflection) 中描述的使值可设置的过程。

关于go - 在 Go 中,如何检查接口(interface)是否实现了结构的所有导出方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59818425/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com