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.
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.htmlgodoc
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.
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