如何将* ast.StructType断言到指定的接口

时间:2014-11-09 12:10:46

标签: go

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

例如

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
}

但没有*ast.StructType.Interface() :(

1 个答案:

答案 0 :(得分:2)

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

编译时间检查很容易(如果没有实现接口,编译器错误):

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

但你甚至不需要实际值,可以写成:

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