Enumerate package functions with reflect?

4,051 views
Skip to first unread message

shka...@gmail.com

unread,
Jun 16, 2013, 10:19:28 AM6/16/13
to golan...@googlegroups.com
Is it possible to list all functions in a package (not methods) via reflect. E.g.

package example

func Test1() int { return 0 }
func Test2() int { return 0 }

In the example above I need to list Test1 and Test2. Is it possible?

Thank you,
Serge

Jan Mercl

unread,
Jun 16, 2013, 12:00:17 PM6/16/13
to shka...@gmail.com, golang-nuts

fortunately it's not possible.

-j

chris dollin

unread,
Jun 16, 2013, 12:24:53 PM6/16/13
to shka...@gmail.com, golang-nuts
On 16 June 2013 15:19, <shka...@gmail.com> wrote:
Is it possible to list all functions in a package (not methods) via reflect.

No.

This allows the linker to quietly drop on the floor
unreferenced functions, which is generally a Good Thing.
 
In the example above I need to list Test1 and Test2. Is it possible?

Have your own map of names to functions -- for the functions it
actually makes sense for -- and initialise it in init.

Chris

--
Chris "allusive" Dollin

rocky

unread,
Jun 16, 2013, 1:36:09 PM6/16/13
to golan...@googlegroups.com, shka...@gmail.com
Actually, if you willing to do a bit of work and have the source code around you can probably list the names functions using go/ast and go/parser.  See http://play.golang.org/p/_MKx4YTuvs which is a tiny modification of http://golang.org/pkg/go/ast/#example_Inspect

Run that, you'll see:

         7  .  .  0: *ast.FuncDecl {
     8  .  .  .  Name: *ast.Ident {
     9  .  .  .  .  NamePos: 3:6
    10  .  .  .  .  Name: "Test1"
...
    53  .  .  1: *ast.FuncDecl {
    54  .  .  .  Name: *ast.Ident {
    55  .  .  .  .  NamePos: 7:6
    56  .  .  .  .  Name: "Test2"

    99  .  .  2: *ast.FuncDecl {
   100  .  .  .  Name: *ast.Ident {
   101  .  .  .  .  NamePos: 11:6
   102  .  .  .  .  Name: "main"
...

   162  .  Scope: *ast.Scope {
   163  .  .  Objects: map[string]*ast.Object (len = 3) {
   164  .  .  .  "Test1": *(obj @ 11)
   165  .  .  .  "Test2": *(obj @ 57)
   166  .  .  .  "main": *(obj @ 103)
   167  .  .  }
   168  .  }


(Plug for https://code.google.com/p/go-play/. When I run http://play.golang.org/p/_MKx4YTuvs the useful output is truncated. In the local version of go-play I have output scrollbars and I think nicer output display.)

Erik Unger

unread,
Jun 17, 2013, 5:58:09 AM6/17/13
to golan...@googlegroups.com, shka...@gmail.com
I have written a tool for that:


-Erik
Reply all
Reply to author
Forward
0 new messages