将对象传递给其他包中的结构体。

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

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.

huangapple
  • 本文由 发表于 2017年2月5日 18:04:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/42050754.html
匿名

发表评论

匿名网友

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

确定