Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 473
user1742648 Avatar asked Sep 20 '25 05:09

user1742648


1 Answers

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.

like image 126
Ainar-G Avatar answered Sep 22 '25 21:09

Ainar-G