get interface and method name

60 views
Skip to first unread message

Vasiliy Tolstov

unread,
Jul 10, 2019, 4:40:38 PM7/10/19
to golang-nuts
Hi! i have interface like

type AccountService interface {
Create(context.Context) error
}

if i need to get string representation of this interface from passed
AccountService.Create how can i do that?

Now i create POC like this:
parts := strings.Split(runtime.FuncForPC(reflect.ValueOf(iface).Pointer()).Name(),
".")
return parts[len(parts)-2] + "." + parts[len(parts)-1]

it returns string "AccountService.Create"
Does it possible to get this not using runtime? only via reflect and
may be without strings ?

--
Vasiliy Tolstov,
e-mail: v.to...@selfip.ru

Ian Lance Taylor

unread,
Jul 10, 2019, 5:28:07 PM7/10/19
to Vasiliy Tolstov, golang-nuts
Can you show us a working example in the Go playground to demonstrated
what you are looking for?

If your interface is named AccountService, I would not expect any
method to be named AccountService.Create. The Create method will be
defined on other types converted to the interface type, not on the
interface type itself. So I'm not sure what you are actually looking
for.

Ian

Vasiliy Tolstov

unread,
Jul 12, 2019, 5:07:44 AM7/12/19
to Ian Lance Taylor, Vasiliy Tolstov, golang-nuts
чт, 11 июл. 2019 г. в 00:27, Ian Lance Taylor <ia...@golang.org>:
https://play.golang.org/p/VZhO4KdKk-J
I need to return textual representation of interface name and method name.

Martin Schnabel

unread,
Jul 12, 2019, 9:19:10 AM7/12/19
to golan...@googlegroups.com
Because AccountService.Create is a method expression you can get to the
interface type by inspecting its first argument. Then you could check
the interface type for all methods and compare the input and output
parameters. This however is brittle and only works if you can guarantee
that there is no other method in the interface with the same parameter
lists.

So i would think using the runtime package is the only and therefor
best option for what you are asking.

Have fun!
Reply all
Reply to author
Forward
0 new messages