Pass object to struct in other package

江枫思渺然 提交于 2021-01-07 07:55:20

问题


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:


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.



来源:https://stackoverflow.com/questions/42050754/pass-object-to-struct-in-other-package

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!