How to check if an object has a particular method?

A simple option is to declare an interface with just the method you want to check for and then do a type assert against your type like; i, ok := myInstance.(InterfaceImplementingThatOneMethodIcareAbout) // inline iface declaration example i, ok = myInstance.(interface{F()}) You likely want to use the reflect package if you plan to do anything too … Read more

In golang, is it possible to get reflect.Type from the type itself, from name as string?

On 1, yes, kinda: var v1 reflect.Type = reflect.TypeOf((*t1)(nil)).Elem() fmt.Println(v1) // prints “main.t1” No instantiation needed. However, Go doesn’t have type literals, which is I think what you’re asking for. To get the runtime value of a type, you need to have a value of some sort. If you don’t want to or can’t create … Read more

How do I compare two functions for pointer equality in the latest Go weekly?

Note that there is a difference between equality and identity. The operators == and != in Go1 are comparing the values for equivalence (except when comparing channels), not for identity. Because these operators are trying not to mix equality and identity, Go1 is more consistent than pre-Go1 in this respect. Function equality is different from … Read more

Call a Struct and its Method by name in Go?

To call a method on an object, first use reflect.ValueOf. Then find the method by name, and then finally call the found method. For example: package main import “fmt” import “reflect” type T struct {} func (t *T) Foo() { fmt.Println(“foo”) } func main() { var t T reflect.ValueOf(&t).MethodByName(“Foo”).Call([]reflect.Value{}) }

Access struct property by name

Most code shouldn’t need this sort of dynamic lookup. It’s inefficient compared to direct access (the compiler knows the offset of the X field in a Vertex structure, it can compile v.X to a single machine instruction, whereas a dynamic lookup will need some sort of hash table implementation or similar). It’s also inhibits static … Read more

How to get the name of a function in Go?

I found a solution: package main import ( “fmt” “reflect” “runtime” ) func foo() { } func GetFunctionName(i interface{}) string { return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() } func main() { // This will print “name: main.foo” fmt.Println(“name:”, GetFunctionName(foo)) }

Iterate through the fields of a struct in Go

After you’ve retrieved the reflect.Value of the field by using Field(i) you can get a interface value from it by calling Interface(). Said interface value then represents the value of the field. There is no function to convert the value of the field to a concrete type as there are, as you may know, no … Read more