【问题标题】:How to dump methods of structs in Golang?如何在 Golang 中转储结构的方法?
【发布时间】:2014-01-28 05:34:36
【问题描述】:

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

例如:

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

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

有什么好的办法吗?

【问题讨论】:

    标签: go


    【解决方案1】:

    您可以使用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 implements the Bar method:", implementsBar(Foo{}))
    

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

    var _ Barer = Foo{}
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2016-07-30
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多