Home > Backend Development > Golang > How Can I Programmatically List Public Methods in a Go Package?

How Can I Programmatically List Public Methods in a Go Package?

Susan Sarandon
Release: 2025-01-05 10:33:46
Original
800 people have browsed it

How Can I Programmatically List Public Methods in a Go Package?

How to List the Public Methods of a Package in Go

Question:

How can I list all the public methods available in a specific package in Go?

Problem:

Consider the following project structure:

  • main.go:

    package main
    
    func main() {
      // List all public methods here.
    }
    Copy after login
  • libs/method.go:

    package libs
    
    func Result1() {
      fmt.Println("Method Result1")
    }
    
    func Result2() {
      fmt.Println("Method Result2")
    }
    Copy after login

Answer:

While it may seem straightforward to list public methods using reflection, it is unfortunately not directly possible in Go. This is because the compiler optimizes unused functions and removes them from the final executable.

Alternative Approach:

If you need to analyze the package's function declarations statically, you can use the go/parser package:

import (
    "fmt"
    "go/ast"
    "go/parser"
    "go/token"
    "os"
)

func main() {
    set := token.NewFileSet()
    packs, err := parser.ParseDir(set, "sub", nil, 0)
    if err != nil {
        fmt.Println("Failed to parse package:", err)
        os.Exit(1)
    }

    funcs := []*ast.FuncDecl{}
    for _, pack := range packs {
        for _, f := range pack.Files {
            for _, d := range f.Decls {
                if fn, isFn := d.(*ast.FuncDecl); isFn {
                    funcs = append(funcs, fn)
                }
            }
        }
    }

    fmt.Printf("All functions: %+v\n", funcs)
}
Copy after login

This approach will provide you with a list of function declarations, although they are not invokable. To execute these functions, you would need to create a separate file and call them individually.

The above is the detailed content of How Can I Programmatically List Public Methods in a Go Package?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template