英文:
Package imports, cannot use struct from imported package
问题
这可能是一个初学者的错误,但我无法解决这个问题。
在main.go中,我导入了一个包。
import(
"models/users"
)
// ...
func main() {
r.HandleFunc("/users/list", UsersModel.List())
}
该包存储在src/models/users中。
users包的代码如下:
package users
import (
"gopkg.in/mgo.v2"
)
// ...
/**
* User Model
*/
type UsersModel struct {
}
// Add methods to the UsersModel type.
func (m *UsersModel) List() {
// ...
}
当我运行代码时,我得到以下错误:
src\main.go:9: imported and not used: "models/users" src\main.go:20:
undefined: UsersModel
Go代码似乎是有效的,因为如果我使其无效,它会抛出一个错误。如何从users包中导出UsersModel类型?
英文:
This is probably a noob mistake but I cannot figure this out.
In main.go I am importing a package.
import(
"models/users"
)
// ...
func main() {
r.HandleFunc("/users/list", UsersModel.List())
The package is stored in src/models/users
The users package looks like this:
package users
import (
"gopkg.in/mgo.v2"
)
// ...
/**
* User Model
*/
type UsersModel struct {
}
// Add methods to the UsersModel type.
func (m *UsersModel) List() {
// ...
When I run the code I get the following error.
> src\main.go:9: imported and not used: "models/users" src\main.go:20:
> undefined: UsersModel
The go code appears to be valid as if I invalidate it throws an error. How do I export the UsersModel type from the users package?
答案1
得分: 6
你需要在使用UsersModel
之前加上包名users
,像这样:
um := users.UserModel{}
UsersModel.List()
也是错误的:Go语言没有“静态方法”或“类方法”。
英文:
You need to prefix your use of UsersModel
with the package name users
, like so:
um := users.UserModel{}
UsersModel.List()
is also wrong: go doesn't have "static methods" or "class methods".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论