Reputation: 1361
I'm playing with Golang and I want to know if there is a way that can list all the methods or properties I can use on a variable. In Ruby I can simply use some_variable.methods
to get all the methods defined on some_variable
. Is there a similar thing in Golang?
Upvotes: 1
Views: 307
Reputation: 8490
If you only need this in development phase guru development tool can help you a lot.
Upvotes: 2
Reputation: 49275
Yes, you can. With reflection, each reflect.Type
object can enumerate all the methods the actual type exposes. but it's not a very common or idiomatic thing to do in Go:
import (
"fmt"
"reflect"
)
type Foo struct {
}
func (f Foo) Bar() {
}
func (f Foo) Baz() {
}
func main() {
t := reflect.TypeOf(Foo{})
for i := 0; i < t.NumMethod(); i++ {
fmt.Println(t.Method(i).Name)
}
}
// Output:
// Bar
// Baz
This can also be done on reflect.Value
, depending on what you need.
But the real question is - what are you trying to achieve here? Are you trying to check if a type implements an interface or something like this? There probably is a simpler solution to your goal. What is your actual goal?
Upvotes: 6