导入包,无法使用导入包中的结构体。

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

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".

huangapple
  • 本文由 发表于 2014年8月6日 00:14:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/25143626.html
匿名

发表评论

匿名网友

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

确定