duandu1377 2015-02-27 13:41
浏览 228
已采纳

在go中使用和分配其他文件(包)的变量

I have a http server using mongodb as a backend db, I wrapped the db operations in a separate file (package), and I don't want to make a connection every time, So I think make a global session and copy it like this maybe a good idea. So this is so far I've got:

File server.go in which I start the http server, and I also want to init the mongodb connection from here, for I don't know other way to make a connection that could live through the whole life of the http server so far :-(

package main

import(
    "./mylib"
    "net/http"
)
...
func main(){
    dbutil.MySession, err := dbutil.ConnectDb()
    if err != nil {
       panic(err)
    }
    // I will just omit the http server config code for convenience
    http.HandleFunc(...)
    http.HandleFunc(...)
}
...

And here is the file dbutil.go which contains the variable MySession. By the way, the total dir structure of them is like this, should be fine:

.
├── mylib
│   └── dbutil.go
└── server.go

And in dbutil.go:

package dbutil
import (
  ...
)

var MySession *mgo.Session
func ConnectDb() (*mgo.Session, error){
   session, err := mgo.Dial("127.0.0.1")
   if err != nil {
       return nil, err
   }
   return session, nil
}

But when I compile them and run the server, it complains that:

# command-line-arguments
./server.go:28: cannot declare name dbutil.MySession

I notice that if I change dbutil.MySession, err := dbutil.ConnectDb() to dbutil.MySession, err = dbutil.ConnectDb() things will not work either.

So How Can I assign the global Variable MySession in this case? Or did I do something wrong (try to use a variable of other file) at the first place?

  • 写回答

1条回答 默认 最新

  • dqiz20794 2015-02-27 13:46
    关注

    The Short variable declaration := creates new variables. The name of the new variables cannot contain package names, but yours does:

    dbutil.MySession, err := dbutil.ConnectDb()
    

    Just don't use the short variable declaration:

    var err error
    dbutil.MySession, err = dbutil.ConnectDb()
    // ...rest of your code
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记