doujuchuan9915 2017-10-25 01:48
浏览 17
已采纳

如何使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. :)

  • 写回答

2条回答 默认 最新

  • duanbigan7765 2017-10-25 05:26
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?