将对象传递给其他包中的struct [英] Pass object to struct in other package
问题描述
我有一个主要功能,我在其中初始化一个变量,一个客户端.例如:
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?
推荐答案
在其余的程序包中,您必须添加一个构造函数,例如:
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.
这篇关于将对象传递给其他包中的struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!