Go:遇到意外错误

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

Go: Getting unexpected error

问题

在我的控制器包中,我有一个名为AppContext的结构体,它看起来像这样:

  1. type AppContext struct {
  2. db *sql.DB
  3. }
  4. func (c *AppContext) getDB() *sql.DB {
  5. return c.db
  6. }

然后,在我的主包中,我有以下代码:

  1. func main() {
  2. db, err := sql.Open("mysql",
  3. //其他信息)
  4. if err != nil {
  5. log.Fatal(err)
  6. return
  7. }
  8. err = db.Ping()
  9. if err != nil {
  10. log.Fatal(err)
  11. return
  12. }
  13. defer db.Close()
  14. appC := controller.AppContext{db}
  15. }

在构建时,我遇到了这个意外的错误:

  1. implicit assignment of unexported field 'db' in controller.AppContext literal

我尝试查找这个错误,但没有找到太多信息。有没有办法解决这个问题?

英文:

In my controller package, I have a AppContext struct that looks like this:

  1. type AppContext struct {
  2. db *sql.DB
  3. }
  4. func (c *AppContext) getDB() *sql.DB {
  5. return c.db
  6. }

Then I have the following codes in my main package:

  1. func main {
  2. db, err := sql.Open("mysql",
  3. //other info)
  4. if err != nil {
  5. log.Fatal(err)
  6. return
  7. }
  8. err = db.Ping()
  9. if err != nil {
  10. log.Fatal(err)
  11. return
  12. }
  13. defer db.Close()
  14. appC := controller.AppContext{db}
  15. }

When building it, I get this unexpected error:

  1. implicit assignment of unexported field 'db' in controller.AppContext literal

I tried looking that error up, but could not find much information on it. Is there a way to resolve this problem?

答案1

得分: 1

根据评论所说,db没有被导出,因此无法从其他包中访问。

在Go语言中,通常使用名为NewMyStructure的函数来初始化结构体,例如:

  1. func NewAppContext(db *sql.DB) AppContext {
  2. return AppContext{db: db}
  3. }

然后在主函数中使用:

  1. appC := controller.NewAppContext(db)
英文:

As said in the comment, db is not exported, so inaccessible from other packages.

In Go, initialization of structures is usually done with a function called NewMyStructure, so for example:

  1. func NewAppContext(db *sql.DB) AppContext {
  2. return AppContext{db: db}
  3. }

and then in your main:

  1. appC := controller.NewAppContext(db)

huangapple
  • 本文由 发表于 2015年5月24日 04:42:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/30417386.html
匿名

发表评论

匿名网友

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

确定