如何在Go中从外部包访问结构 [英] How to access a struct from an external package in 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
}
但是在main.go
文件中,结构Product
是未定义的.如何导入该结构?
But in the main.go
file the struct Product
is undefined. How do I import the struct?
推荐答案
在Go中,您导入的是完整的" 包,而不是包中的函数或类型.
(有关更多详细信息,请参见此相关问题:在golang中C ++的"using"等效项是什么)
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)
有关import
关键字的语法和更深入的说明,请参见规范:导入声明.进口报关单.
See Spec: Import declarations for syntax and deeper explanation of the import
keyword and import declarations.
导入包后,可以使用引用其导出的标识符 ="https://golang.org/ref/spec#Qualified_identifiers" rel ="nofollow noreferrer">合格的标识符,其格式为:packageName.Identifier
.
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"`
}
这篇关于如何在Go中从外部包访问结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!