查找对象支持的所有导入接口。

huangapple go评论70阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年11月19日 17:22:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/33799735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定