Can an init function in golang return a value?

huangapple go评论78阅读模式
英文:

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 ...
}

huangapple
  • 本文由 发表于 2015年11月25日 16:38:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/33911808.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定