如何在Golang中转储结构体的方法?

huangapple go评论67阅读模式
英文:

How to dump methods of structs in Golang?

问题

Golang的"fmt"包中有一个名为Printf("%+v", anyStruct)的转储方法。我正在寻找一种方法来转储一个结构体以及它的方法

例如:

type Foo struct {
    Prop string
}
func (f Foo)Bar() string {
    return f.Prop
}

我想检查在类型为Foo的已初始化实例中是否存在Bar()方法(不仅仅是属性)。

有没有什么好的方法可以做到这一点?

英文:

The Golang "fmt" package has a dump method called Printf("%+v", anyStruct). I'm looking for any method to dump a struct and its methods too.

For example:

type Foo struct {
    Prop string
}
func (f Foo)Bar() string {
    return f.Prop
}

I want to check the existence of the Bar() method in an initialized instance of type Foo (not only properties).

Is there any good way to do this?

答案1

得分: 56

你可以使用reflect包列出一个类型的方法。例如:

fooType := reflect.TypeOf(&Foo{})
for i := 0; i < fooType.NumMethod(); i++ {
    method := fooType.Method(i)
    fmt.Println(method.Name)
}

你可以在这里尝试一下:http://play.golang.org/p/wNuwVJM6vr

在此基础上,如果你想检查一个类型是否实现了某个方法集,你可以使用接口和类型断言来简化操作。例如:

func implementsBar(v interface{}) bool {
    type Barer interface {
        Bar() string
    }
    _, ok := v.(Barer)
    return ok
}

...
fmt.Println("Foo实现了Bar方法:", implementsBar(Foo{}))

或者,如果你只是想在编译时断言一个特定类型是否具有这些方法,你可以简单地在某个地方包含以下代码:

var _ Barer = Foo{}
英文:

You can list the methods of a type using the reflect package. For example:

fooType := reflect.TypeOf(&amp;Foo{})
for i := 0; i &lt; fooType.NumMethod(); i++ {
	method := fooType.Method(i)
	fmt.Println(method.Name)
}

You can play around with this here: http://play.golang.org/p/wNuwVJM6vr

With that in mind, if you want to check whether a type implements a certain method set, you might find it easier to use interfaces and a type assertion. For instance:

func implementsBar(v interface{}) bool {
	type Barer interface {
		Bar() string
	}
	_, ok := v.(Barer)
	return ok
}

...
fmt.Println(&quot;Foo implements the Bar method:&quot;, implementsBar(Foo{}))

Or if you just want what amounts to a compile time assertion that a particular type has the methods, you could simply include the following somewhere:

var _ Barer = Foo{}

huangapple
  • 本文由 发表于 2014年1月28日 13:34:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/21397653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定