从不同的包中访问结构体的方法

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

Accessing methods on a struct from a different package

问题

我的问题与这个问题有些相关,但我不是在扩展现有类型,而是在创建自己的类型。我的目标是像Java中这样做:

JsonClient j = new JsonClient()
j.setUrl("x.com")
j.setMethod(GET)
j.setData("{crap: morecrap}")
String result = j.send

但是在Go语言中,我能做的最好的是:

config := jsonclient.Config{}
config.Url = "http://foaas.com/version"
config.Data = []byte(`{datadatadata}`)
config.Method = "GET"

s, err := jsonclient.NewClient(&config)
checkErr(err)

response := jsonclient.Dial(s)

我不希望有一个配置对象来设置jsonclient实例,因为它只在jsonclient类中有意义,所以我应该能够使用jsonclient.SetUrl等方法,这样更高效,也能帮助我理解一些在Go语言中我所缺少的关键点。

你可以在这里找到jsonclient。

英文:

My question is somewhat related to this but rather than extending an existing type im trying to create my own. My goal is to have something like this, coming from java

JsonClient j = new JsonClient()
j.setUrl("x.com")
j.setMethod(GET)
j.setData("{crap: morecrap}")
String result = j.send

But in go the best i can do is

config := jsonclient.Config{}
config.Url = "http://foaas.com/version"
config.Data = []byte(`{datadatadata}`)
config.Method = "GET"

s, err := jsonclient.NewClient(&config)
checkErr(err)

response := jsonclient.Dial(s)

I do not wish to have a config object just to setup a jsonclient
instance, since it only has meaning in the, dont hit me, jsonclient
class so i should be able to do jsonclient.SetUrl and so on, seams more
efficient and would help me understand a couple of key points im missing
in go.

You can find the jsonclient here

答案1

得分: 4

你可以调用另一个包中的类型的方法,前提是这些方法是公开的(即以大写字母开头)。因此,你可以向你的类型添加这样的方法,没有任何限制:你只需要将它们命名为SetUrl而不是setUrl

英文:

You can call methods on types from another package provided those methods are exported (that is, starting with a capital letter). So there is nothing stopping you from adding such methods to your type: you'd just need to name them e.g. SetUrl instead of setUrl.

huangapple
  • 本文由 发表于 2015年5月23日 22:01:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/30413581.html
匿名

发表评论

匿名网友

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

确定