dsh7551 2016-09-26 19:10
浏览 119

如何在Go中从外部包访问结构

I'm trying to import a struct from another package in the following file:

// main.go
import "path/to/models/product"    
product = Product{Name: "Shoes"}

// models/product.go
type Product struct{
 Name string
}

But in the main.go file the struct Product is undefined. How do I import the struct?

  • 写回答

1条回答 默认 最新

  • doufeng3602 2016-09-26 19:15
    关注

    In Go you import "complete" packages, not functions or types from packages.
    (See this related question for more details: What's C++'s `using` equivalent in golang)

    See Spec: Import declarations for syntax and deeper explanation of the import keyword and import declarations.

    Once you import a package, you may refer to its exported identifiers with qualified identifiers which has the form: packageName.Identifier.

    So your example could look like this:

    import "path/to/models/product"
    import "fmt"
    
    func main() {
        p := product.Product{Name: "Shoes"}
        // Use product, e.g. print it:
        fmt.Println(p) // This requires `import "fmt"`
    }
    
    评论

报告相同问题?