Home > Backend Development > Golang > How Can I Discover Exported Types from External Go Packages?

How Can I Discover Exported Types from External Go Packages?

Patricia Arquette
Release: 2024-12-30 05:40:09
Original
344 people have browsed it

How Can I Discover Exported Types from External Go Packages?

Discovering Defined Types in External Packages

In Go, type definitions are exported when their names begin with uppercase letters. To access these types from another package, you can use the go/importer package.

Solution:

package main

import (
    "fmt"

    "go/importer"

    demo "example.com/path/to/demo" // import the package containing the types
)

func main() {
    pkg, err := importer.Default().Import("example.com/path/to/demo")
    if err != nil {
        fmt.Println("error:", err)
        return
    }

    // Get the names of all exported types in the package
    for _, declName := range pkg.Scope().Names() {
        fmt.Println(declName)
    }
}
Copy after login

This code will print the following output, which lists the names of the exported types defined in the demo package:

People
UserInfo
Copy after login

Note: Using go/importer on the Go Playground may result in an error.

The above is the detailed content of How Can I Discover Exported Types from External Go Packages?. 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