如何使func main()中设置的数据库实例可用于其他程序包?

I’m writing my first go web app and I have the following structure:

.
├── main.go
├── model
│   ├── model.go
│   └── book.go
├── route
│   └── route.go
└── view
    └── view.go

/main.go is where my main() is located. In that file I also defined a variable Env where I’ll keep the instance of my database (at least that’s the plan).

In /main.go I do

import "project/view"

type Env struct {
    db models.Collection
}

// rest of the code

func main() {
    db, err := models.NewDB()
    // etc
    MyEnv := &Env{db}
    // etc
}

But the thing is that in /view/view.go I need to call methods defined in /model/book.go and I thought the way to do that was through the MyEnv.db instance but of course I get an error:

view/view.go:13:14: undefined: Env

^^ Any help to solve that problem would be appreciated or any lead on how to better structure my project. :)

If you want to use a name (variable, type, etc.) from another package, you need to import that package, e.g. with import "view" you could do view.Something in your main package.

Now you cannot import a main package, this means that your view package cannot import main to call main.Env. So you have to use another way, some possibilities are:

  1. Put the Env type in the view package and then in your main package just declare a var myEnv = view.Env{}.

  2. Put the Env type in its own package env which you then import in both view and main

  3. Instead of using a concrete type Env you could use an interface type in the view package. This type should only expose the functions that you need from it. Then you can implement that type in your main package and pass an instance of that to view.

Define it on a top level of you code on main

var MyEnv Env

 func main(){
     MyEnv = &Env{}

  }