英文:
How to import structs from another package in Go
问题
我正在尝试将以下结构体导入到Golang的一个单独包中:
package models
type Category struct {
Title string
Description string
Parent *Category
ParentId int
}
导入到package controllers
中的代码如下:
import (
"website.com/Owner/blog/app/models"
)
func (c Category) Update() {
// 在这里做一些操作
}
然而,我得到了unresolved type Category
的错误。我应该如何将一个结构体导入到一个单独的包中?
英文:
I am trying to import the following struct into a separate package in Golang
package models
type Category struct {
Title string
Description string
Parent *Category
ParentId int
}
into package controllers
as follows
import(
"website.com/Owner/blog/app/models"
)
func (c Category) Update(){
//do something here
}
However, I get the error unresolved type Category
How should I go about importing a struct into a separate package with Go?
答案1
得分: 4
你需要完全限定你的名称:不要使用Category
,而是使用models.Category
。这里的文档可以帮助你入门。你可以这样做:
import "fmt"
func main() {
fmt.Println("Hello")
}
或者:
import f "fmt"
func main() {
f.Println("Hello")
}
或者完全放弃限定(然而,这被认为是不好的风格:在查看代码时,能够一眼看出某个结构或函数来自哪里非常方便):
import . "fmt"
func main() {
// 这是从哪里来的?如果没有对包有详细了解,很难知道
Println("Hello")
}
你还可以为了更方便地在本地使用,对远程结构进行“typedef”:
import "website.com/Owner/blog/app/models"
type Category models.Category
但请注意,这会创建一个新类型,尽管底层类型相同。
英文:
You need to fully qualify your names: don't use Category
, but use models.Category
. The doc there should get you started. You can do:
import "fmt"
func main() {
fmt.Println("Hello")
}
Or:
import f "fmt"
func main() {
f.Println("Hello")
}
Or ditch the qualification entirely (however, this is considered poor style: being able to see, at a glance, where some structure or function comes from is very handy when looking at code):
import . "fmt"
func main() {
// Where does that come from ? Hard to know without
// intimate knowledge of the package
Println("Hello")
}
One last thing you can do is to 'typedef' your remote structure for easier use locally:
import "website.com/Owner/blog/app/models"
type Category models.Category
Note however that it create a new type, although with the same underlying type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论