英文:
Pass object to struct in other package
问题
我有一个主函数,在其中初始化了一个变量,一个客户端。例如:
func main() {
myClient := my.MustNewClient("localhost")
}
现在我想将这个客户端传递给另一个包,但出于某种原因,我无法弄清楚如何做到这一点。我的包看起来像这样:
package rest
import (
"net/http"
"github.com/Sirupsen/logrus"
)
type AssetHandler struct {
mc my.Client
}
func (f AssetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logrus.Info("bla")
// 在这里我想使用客户端
mc.SomeFunctionIntheClient()
}
所以我的问题是,如何在我的包中(不在main函数中)使用客户端?
英文:
I have a main function, where I initiate a variable, a client. For example:
func main() {
myClient := my.MustNewClient("localhost")
}
Now I want to pass this client to another package, but for some reason I cannot figure out how to do this. My package looks like this:
package rest
import (
"net/http"
"github.com/Sirupsen/logrus"
)
type AssetHandler struct {
mc my.Client
}
func (f AssetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logrus.Info("bla")
// here I want to use the client
mc.SomeFunctionIntheClient()
}
So my question is, how do I use the client (out of main) in my package?
答案1
得分: 1
在包rest
中,你需要添加一个构造函数,如下所示:
func NewAssetHandler(mc my.Client) AssetHandler {
return AssetHandler{mc}
}
然后你需要在main
函数中实例化该处理程序。
否则,你将需要创建一个单独的包来存储全局变量。主包本身不能用于此,因为它无法从其他地方访问。
英文:
In the package rest you have to add a constructor function like:
func NewAssetHandler(mc my.Client) AssetHandler {
return AssetHandler{mc}
}
Then you have to instantiate the handler from your main function.
Otherwise you would have to create a separate package where you store global variables. The main package itself can not be used for this because it can't be accessed from somewhere else.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论