如何在 Golang 中转储结构体的方法? [英] How to dump methods of structs in Golang?

查看:30
本文介绍了如何在 Golang 中转储结构体的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Golang "fmt" 包有一个名为 Printf("%+v", anyStruct) 的转储方法.我正在寻找任何方法来转储结构及其方法.

例如:

type Foo struct {道具字符串}func (f Foo)Bar() 字符串 {返回 f.Prop}

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

有什么好的办法吗?

解决方案

您可以使用 reflect 包列出类型的方法.例如:

fooType :=reflect.TypeOf(Foo{})对于我:= 0;我<fooType.NumMethod();我++ {方法 := fooType.Method(i)fmt.Println(method.Name)}

你可以在这里玩这个:http://play.golang.org/p/wNuwVJM6vr>

考虑到这一点,如果您想检查一个类型是否实现了某个方法集,您可能会发现使用接口和类型断言更容易.例如:

func implementsBar(v interface{}) bool {类型 Barer 接口 {Bar() 字符串}_, 好的 := v.(Barer)返回好}...fmt.Println("Foo 实现了 Bar 方法:", implementsBar(Foo{}))

或者,如果您只是想要一个特定类型具有方法的编译时断言,您可以简单地在某处包含以下内容:

var _ Barer = Foo{}

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?

解决方案

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

fooType := reflect.TypeOf(Foo{})
for i := 0; i < 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("Foo implements the Bar method:", 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{}

这篇关于如何在 Golang 中转储结构体的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆