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)) }

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{}) }

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

Identify non builtin-types using reflect

Some background First let’s clear some things related to types. Quoting from Spec: Types: A type determines the set of values and operations specific to values of that type. Types may be named or unnamed. Named types are specified by a (possibly qualified) type name; unnamed types are specified using a type literal, which composes … Read more

Instance new Type (Golang)

So, if I understand your question correctly, you are asking about how you can create an object when you just have the name of the type as string. So, for example, you might have a string “MyStruct” and you want to create an object of this type. Unfortunately, that’s not easily possible because Go is … Read more

Convert between slices of different types

As others have said, casting the pointer is considered bad form in Go. Here are examples of the proper Go way and the equivalent of the C array casting. WARNING: all code untested. The Right Way In this example, we are using the encoding/binary package to convert each set of 4 bytes into an int32. … Read more