Home > Backend Development > Golang > How Can I Access All Exported Types from a Specific Go Package?

How Can I Access All Exported Types from a Specific Go Package?

Mary-Kate Olsen
Release: 2024-12-13 11:18:15
Original
485 people have browsed it

How Can I Access All Exported Types from a Specific Go Package?

Accessing Exported Types Across Packages

In Go, exported types are accessible by other packages. This allows for reuse and modularity in code design. However, how can you access all the defined exported types from a specific package?

Consider the following example:

package demo

type People struct {
    Name string
    Age  uint
}

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

In a separate package, let's say,

import "demo"
Copy after login

From this other package, we seek to retrieve all exported types defined within the demo package. To achieve this, we can leverage the go/importer package:

package main

import (
    "fmt"

    "golang.org/x/tools/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

This code imports the demo package using the importer and iterates over the defined names within its scope. The resulting output will list all exported types, in this case:

People
UserInfo
Copy after login

However, it's worth noting that using this approach may result in an error on the Go Playground.

The above is the detailed content of How Can I Access All Exported Types from a Specific 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