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

huangapple go评论72阅读模式
英文:

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"`
}

huangapple
  • 本文由 发表于 2016年9月27日 03:10:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/39710558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定