英文:
How to access a struct from an external package in Go
问题
我正在尝试从另一个包中导入一个结构体到以下文件中:
// main.go
import "path/to/models/product"
product = Product{Name: "Shoes"}
// models/product.go
type Product struct{
Name string
}
但是在 main.go
文件中,结构体 Product
未定义。我该如何导入这个结构体?
英文:
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
得分: 8
在Go语言中,你导入的是“完整的”包,而不是从包中导入函数或类型。
(有关更多详细信息,请参见此相关问题:https://stackoverflow.com/questions/38904423/whats-cs-using-equivalent-in-golang)
有关import
关键字和导入声明的语法和更深入的解释,请参阅规范:导入声明。
一旦你导入了一个包,你可以使用限定标识符来引用其导出标识符,其形式为:packageName.Identifier
。
所以你的示例可能如下所示:
import "path/to/models/product"
import "fmt"
func main() {
p := product.Product{Name: "Shoes"}
// 使用product,例如打印它:
fmt.Println(p) // 这需要`import "fmt"`
}
英文:
In Go you import "complete" packages, not functions or types from packages.
(See this related question for more details: https://stackoverflow.com/questions/38904423/whats-cs-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"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论