Go:遇到意外错误

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

Go: Getting unexpected error

问题

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

type AppContext struct {
    db *sql.DB
}

func (c *AppContext) getDB() *sql.DB {
    return c.db
}

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

func main() {
    db, err := sql.Open("mysql",
        //其他信息)
    if err != nil {
        log.Fatal(err)
        return
    }
    err = db.Ping()
    if err != nil {
        log.Fatal(err)
        return
    }
    defer db.Close()
    appC := controller.AppContext{db}
}

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

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

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

英文:

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

type AppContext struct {
      db *sql.DB
}

func (c *AppContext) getDB() *sql.DB {
      return c.db
}

Then I have the following codes in my main package:

func main {

db, err := sql.Open("mysql",
		//other info)
	if err != nil {
		log.Fatal(err)
                return 
	}
        err = db.Ping() 
        if err != nil {
	        log.Fatal(err)
                return
        }
	defer db.Close()
        appC := controller.AppContext{db}

}

When building it, I get this unexpected error:

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的函数来初始化结构体,例如:

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

然后在主函数中使用:

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:

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

and then in your main:

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:

确定