gpt4 book ai didi

go - 如何将 *ast.StructType 断言到指定接口(interface)

转载 作者:IT王子 更新时间:2023-10-29 01:43:01 25 4
gpt4 key购买 nike

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

例如

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

最佳答案

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

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

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

但您甚至不需要实际值,可以将其写为:

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

关于go - 如何将 *ast.StructType 断言到指定接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26827992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com