user1742648
user1742648

Reputation: 57

get golang interface name dynamically

I have a interface:

type Printer interface {
    Print(s string)
}

and a func:

func fxyz(name string) {
    ....
}

I want to call fxyz with "Printer", but I don't want to hard code the string.

How could I get the Interface Name using reflection or other approach?

Upvotes: 4

Views: 5861

Answers (1)

Ainar-G
Ainar-G

Reputation: 36189

If you want to get the name of the interface, you can do that using reflect:

name := reflect.TypeOf((*Printer)(nil)).Elem().Name()
fxyz(name)

Playground: http://play.golang.org/p/Lv6-qqqQsH.

Note, you cannot just take reflect.TypeOf(Printer(nil)).Name() because TypeOf will return nil.

Upvotes: 7

Related Questions