Home > Backend Development > Golang > How Can I Retrieve All Exported Types from a Go Package Without Importing It?

How Can I Retrieve All Exported Types from a Go Package Without Importing It?

Patricia Arquette
Release: 2024-12-26 03:11:09
Original
447 people have browsed it

How Can I Retrieve All Exported Types from a Go Package Without Importing It?

How to Inspect Exported Types from a Package

In Go, types can be exported from a package to make them accessible to other packages. Sometimes, it may be necessary to access information about these exported types without directly importing the package. This article will explore how to get all defined types exported from a particular package using the go/importer package.

Question:

Consider the following demo package:

package demo

type People struct {
    Name string
    Age  uint
}

type UserInfo struct {
    Address  string
    Hobby    []string
    NickNage string
}
Copy after login

In another package, how can we retrieve all the exported types from the demo package?

Answer:

To achieve this, we can use the go/importer package, which provides an API for importing packages and introspecting their contents. Here's how to do it:

import (
    "fmt"
    "go/importer"
)

func main() {
    pkg, err := importer.Default().Import("demo")
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    for _, declName := range pkg.Scope().Names() {
        fmt.Println(declName)
    }
}
Copy after login

In this code, we first import the demo package and then use the importer.Default().Import("demo") function to get the *Package representing the demo package.

Next, we iterate over the Names of the package's Scope, which contains the names of all the exported types in that package. These names are then printed to the standard output.

Note: When running this code in Go Playground, you will likely encounter an error. This is because the Go Playground's environment does not have the ability to retrieve package metadata from external sources.

The above is the detailed content of How Can I Retrieve All Exported Types from a Go Package Without Importing It?. 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