繁体   English   中英

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

[英]In Go, how to check that an interface implements all of a struct's exported methods?

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

在较高的水平,这在我看来,我能得到reflect.Value两者的界面和结构,并调用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())
}

我可以调用 get the number of the person的方法,但不能personInterface ,因为这会因错误消息而恐慌

反射:在零值上调用reflect.Value.NumMethod

这是完整的错误:

> 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实现的方法数量,更一般地说,我将如何检查接口是否实现了结构的所有导出方法?

要转换mkopriva我们去游乐场评论一个答案, reflect.ValueOf()需要一个指针调用的接口( 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 ) 中描述的使值可设置的过程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM