如何将 *ast.StructType 断言为指定的接口类型?

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

How to assert *ast.StructType to specified interface

问题

我可以断言由ast.TypeSpec和ast.StructType表示的结构体是否实现了已知的接口类型吗?

例如:

func assertFoo(spec *ast.TypeSpec) bool {
    // spec.Name == "MyStruct"
    st, _ := spec.Type.(*ast.StructType)
    // 我想知道"MyStruct"是否实现了"FooInterface"
    _, ok := st.Interface().(FooInterface)
    return ok
}

但是没有*ast.StructType.Interface()方法 如何将 *ast.StructType 断言为指定的接口类型?

英文:

Can I assert a struct represented by *ast.TypeSpec and *ast.StructType to implement a known interface type?

For example

func assertFoo(spec *ast.TypeSpec) bool {
    // spec.Name == "MyStruct"
    st, _ := spec.Type.(*ast.StructType)
    // I want to know whether "MyStruct" implements "FooInterface" or not
    _, ok := st.Interface().(FooInterface)
    return ok
}

but there is no *ast.StructType.Interface() 如何将 *ast.StructType 断言为指定的接口类型?

答案1

得分: 2

第一个问题是你想要做什么?

编译时检查很容易(如果接口未实现,则编译器会报错):

func assertFoo(t *ast.StructType) {
    var _ FooInterface = t
}

但你甚至不需要实际的值,可以这样写:

func assertFoo() {
    var _ FooInterface = (*ast.StructType)(nil)
}
英文:

The first question would be what are you trying to do?

Compile time check is easy (compiler error if the interface is not implemented):

func assertFoo(t *ast.StructType) {
    var _ FooInterface = t
}

But you don't even need the actual value and can write this as:

func assertFoo() {
    var _ FooInterface = (*ast.StructType)(nil)
}

huangapple
  • 本文由 发表于 2014年11月9日 20:10:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/26827992.html
匿名

发表评论

匿名网友

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

确定