英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论