gpt4 book ai didi

go - 如何在 GO 的全局范围内存储和获取指针引用

转载 作者:数据小太阳 更新时间:2023-10-29 03:29:15 25 4
gpt4 key购买 nike

我有以下代码:

package main


func main() {
// create a pointer referece of session of Mongo DB
session := mongoDB.CreateSession()

// Question 1 : How to store a pointer reference in a global scope and using anywhere of the code

defer session.Close()

// Note I suppose that the code call to handler methods that call to the Process in the package controller(the last one code)

}

创建MongoDB session 的代码

package mongoDB


func CreateSession() *mgo.Session {
session, err := mgo.Dial("192.168.0.108:27017/databasename")
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
return session
}

我想使用存储在 main 中的指针引用的地方

package controller


func Process() {

// Question 2 : How can a get the pointer reference store in Question 1 if is posible
collection := mongoDB.CreateCollection(session, "namedatabase", "colectionData")
mongoDB.InsertData(collection, "Ale", "45646565")

}

这个想法是为了避免在为所有项目创建的每个函数中通过引用传递 session (我在主函数中的指针引用)。

最佳答案

您不能让您的controller 包导入main。这不是一个好主意(而且我很确定这甚至是不可能的)。但这并不意味着您不能在 controller 中拥有全局 session 变量。

你可以试试这个:

package main

import (
"controller"
"mongoDB"
)

func main() {
// create a pointer referece of session of Mongo DB
session := mongoDB.CreateSession()
defer session.Close()

controller.SetDBSession(session) // Or controller.Init or whatever you like

controller.Process()
}

然后在 controller 包中你有:

package controller

import "mongoDB"

// Global session var for the package
var session mongoDB.Session

// SetDBSession sets the mongoDB session to be used by the controller package.
// This function must be called before calling Process()
func SetDBSession(s mongoDB.Session) {
session = s
}

func Process() {
collection := mongoDB.CreateCollection(session, "namedatabase", "colectionData")
mongoDB.InsertData(collection, "Ale", "45646565")
}

使用此解决方案,您只需将 session 传递给 Controller ​​包一次,让 main 负责 session 的创建和关闭。

关于go - 如何在 GO 的全局范围内存储和获取指针引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23230888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com