Get name of struct implementing interface using interface method, reflection

484 views
Skip to first unread message

Glen Newton

unread,
May 8, 2020, 4:33:57 PM5/8/20
to golang-nuts
Hello,

I would like to get the name of the struct implementing an interface (using a method in the interface). I could just have the MyInterface.StructName() method in each implementing struct which just did a return "myname" but I would prefer to do this using reflection and without having to replicate the same method in all implementations,  I have tried using an embedded struct here[1], but it prints the name of the embedded struct. Is there a way to do this?

Why: I have multiple implementations and want to be able to record which implementation was used.

Thanks,
Glen


Ian Lance Taylor

unread,
May 8, 2020, 4:37:53 PM5/8/20
to Glen Newton, golang-nuts
On Fri, May 8, 2020 at 1:34 PM Glen Newton <glen....@gmail.com> wrote:
>
> I would like to get the name of the struct implementing an interface (using a method in the interface). I could just have the MyInterface.StructName() method in each implementing struct which just did a return "myname" but I would prefer to do this using reflection and without having to replicate the same method in all implementations, I have tried using an embedded struct here[1], but it prints the name of the embedded struct. Is there a way to do this?
>
> Why: I have multiple implementations and want to be able to record which implementation was used.

Perhaps you could use reflect.TypeOf(v).String().

Ian

Glen Newton

unread,
May 8, 2020, 4:43:01 PM5/8/20
to golang-nuts
Thanks!

Oh no, when I try that here: https://play.golang.org/p/RV-S4MJWYUi
Did not work: similar results: instead of:
BaseFoo
BaseFoo
BaseFoo
BaseFoo

now I get:
main.BaseFoo main.BaseFoo main.BaseFoo main.BaseFoo

Other suggestions? :-)

Thanks,
Glen

Marcin Romaszewicz

unread,
May 8, 2020, 5:35:53 PM5/8/20
to Glen Newton, golang-nuts
Go isn't polymorphic, whenever your String() function is called, it's on BaseFoo, you have to do it like this:


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/53e2c85d-9417-4108-abe3-da436b146fb7%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages