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?
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)