lundi 20 janvier 2020

How to get a list of a struct's methods in Go?

I have a library in which there are both Client and MockClient structs which both implement the same ClientInterface interface. I would like to write unit tests to keep these structs in sync so that they not only just implement the interface, but so that MockClient has all of Client's methods. To this end, I would like to get a list of a struct's methods in order to print an informative error message if one of the methods of Client is missing from MockClient.

I've tried adapting How to get the name of a function in Go? to this simplified example:

package main

import (
    "fmt"
    "reflect"
    "runtime"
)

type Person struct {
    Name string
}

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

func main() {
    person := Person{Name: "John Doe"}
    personValue := reflect.ValueOf(&person)

    for i := 0; i < personValue.NumMethod(); i++ {
        fmt.Println(runtime.FuncForPC(personValue.Method(i).Pointer()).Name())
    }
}

What I would like is for this script (shared at https://play.golang.org/p/HwvhEPfWI5I) to print GetName. However, instead, it prints

reflect.methodValueCall

How can I get this script to print the names of *Person's methods?





Aucun commentaire:

Enregistrer un commentaire