英文:
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()
方法
英文:
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()
答案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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论