英文:
Find all imported interfaces that object supports
问题
我有一个类似于os.Stdout
的对象,我想知道它是否支持在我的平台上的io.WriteCloser
接口。我可以获取我的对象的类型,但它并不能告诉我关于接口的任何信息。
package main
import (
"fmt"
"reflect"
"os"
)
func main() {
fmt.Println(reflect.TypeOf(os.Stdout))
}
这段代码会在控制台打印出*os.File
。
我可以手动查找os.File
是否匹配io.WriteCloser
的方法,但我想知道该对象支持的所有接口。
英文:
I have an object like os.Stdout
and I want to know if it supports io.WriteCloser
on my platform. I can get the type of my object, but it doesn't tell me anything about interfaces.
package main
import ("fmt"; "reflect"; "os")
func main() {
fmt.Println(reflect.TypeOf(os.Stdout))
}
This code prints *os.File
to console.
I can manually lookup if os.File
matches io.WriteCloser
methods, but I am curious to get all interfaces that this object supports.
答案1
得分: 1
这不是一个确切的回答,因为它不是针对运行时的。不过我认为它可能会有用。
请查看 https://golang.org/lib/godoc/analysis/help.html
godoc
具有静态分析功能。它可以显示类型实现的关系。
例如,你可以运行 godoc -http=:8081 -analysis=type
,并获取所有包的文档以及类型分析信息。
英文:
It's not an exactly answer on the question, because it is not for runtime. Anyway I think it maybe useful
Take a look on https://golang.org/lib/godoc/analysis/help.html
godoc
has static analysis features. And it can display your type implements relations.
For example you can run godoc -http=:8081 -analysis=type
and get all your packages documentation with type analysis.
答案2
得分: 1
对于@Volker关于类型断言的评论的进一步解释,代码如下所示:
_, implements := interface{}(os.Stdout).(io.Reader)
它将os.Stdout
转换为interface{}
类型,然后尝试断言它是一个io.Reader
。类型断言返回两个值;第一个是断言的值(如果断言失败则为nil),第二个是一个布尔值,指示断言是否成功。如果省略捕获第二个返回值,那么断言失败将导致恐慌。
对于替代方案,可能更通用或运行时要求,types包可能有一些基于反射的有用函数:https://godoc.org/golang.org/x/tools/go/types
英文:
To expand on the comment from @Volker regarding type assertions, that would look like this:
_, implements := interface{}(os.Stdout).(io.Reader)
It casts os.Stdout
to an interface{}
type and then attempts to assert that it is an io.Reader
. Type assertions return two values; the first is the asserted value (or nil if assertion fails) and the second is a boolean indicating if the assertion was successful or not. If you omit capturing the second return value then a failed assertion will cause a panic.
For alternative, possibly more generic or runtime requirements the types package may have some useful functions based on reflection: https://godoc.org/golang.org/x/tools/go/types
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论