英文:
Can an init function in golang return a value?
问题
有人可以建议另一种方法来处理在我的server.go程序中在init函数之外初始化数据库吗?
我在我的程序中使用MySQL,并且我的要求是初始化、连接并将处理程序发送给控制器。
英文:
Can any one suggest any another approach to deal with initializing a database outside init function in my server.go program ?
I am using a MySQL in my program and it is my requirement to initialize and connect and send the handler to the controllers.
答案1
得分: 3
你不能通过init()
函数返回一个值,但你可以使用它来初始化全局(包级)变量,所以你可以尝试像这样做:
package mysql
var Conn Connection
func init(){
Conn = ...
}
现在,控制器可以通过导入你的包并访问已经初始化的连接来访问你的连接。
package controllers
import(
"mysql"
)
func abc(){
mysql.Conn ...
}
英文:
You cannot return a value with the init()
function but what you can do is initialize global(package) variables with it so you can try something like that:
package mysql
var Conn Connection
func init(){
Conn = ...
}
And now the controllers can access your connection importing your package and accessing your already initialized connection.
package controllers
import(
"mysql"
)
func abc(){
mysql.Conn ...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论