otiai10
otiai10

Reputation: 4879

How to assert *ast.StructType to specified interface

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() :(

Upvotes: 2

Views: 507

Answers (1)

Arjan
Arjan

Reputation: 21465

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)
}

Upvotes: 2

Related Questions