etcd go clientv3 – 为什么我不能在不循环遍历结果的情况下获取一个值

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

etcd go clientv3 - why can't I get a value without looping through the result

问题

我正在尝试学习Go语言,进展还不错,但我遇到了一些我无法理解的行为。我猜这与etcd无关?

所以,我已经设置了etcd v3,并且有一个键/值对。当我使用'get'(参见[这里][1])检索它时,我本来希望能够使用以下方式检索我的值:

fmt.Println(resp.Kvs.Value)

然而,这样做不起作用,我必须按照示例(在上面的链接中)循环遍历单个结果来暴露它:

for _, ev := range resp.Kvs {
fmt.Printf("%s : %s\n", ev.Key, ev.Value)
}

请问你能帮我理解为什么无法直接检索值,以及为什么需要循环遍历?

英文:

I'm trying to learn go and have been doing ok but I have come across behaviour that I can't understand. I guess it is not really to do with etcd?

So, I have etcd v3 setup with a key/value. When I retrieve it with 'get' (see [here][1]) I would have expected to be able to retrieve my value using:

fmt.Println(resp.Kvs.Value)

however, this doesn't work and I have to do it as per the example (in the link above) and loop through the single result to expose it:

for _, ev := range resp.Kvs {
fmt.Printf("%s : %s\n", ev.Key, ev.Value)
}

Please could you help me understand why retrieving the value directly isn't possible and what is going on that makes the loop necessary?

[1]: https://godoc.org/github.com/coreos/etcd/clientv3#example-KV--Get "get"

答案1

得分: 1

响应对象在获取单个键或多个键时是相同的,因此它必须提供多个结果,即使返回的总数是1。如果你知道只有一个结果,你不需要循环遍历它,可以直接引用第一个结果:

resp.Kvs[0].Value

当然,你应该先确保有结果存在(len(resp.Kvs) > 0),否则会出现错误。

英文:

The response object is the same whether you're getting a single key or many keys, so it must provide for multiple results, even when the total count returned is 1. If you know there's only one result, you're not obliged to loop over it, you can just reference the first result:

resp.Kvs[0].Value

Of course, you should make sure there was a result first (len(resp.Kvs) > 0) or it will panic.

huangapple
  • 本文由 发表于 2017年7月31日 21:50:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/45417781.html
匿名

发表评论

匿名网友

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

确定