<p>I'd like to write a function which accepts a slice of keys and returns the result of traversing a map for each of those keys.</p>
<p>For example, given this map:</p>
<pre><code>m := map[string]interface{}{
"apples": []string{"delicious", "green", "red"},
"oranges": map[string]interface{}{
"foo": 123456,
"bar": "hello, world",
},
}
</code></pre>
<p>we can get the value of the <code>"bar"</code> key in the <code>"oranges"</code> map by writing:</p>
<pre><code>m["oranges"].(map[string]interface{})["bar"]
</code></pre>
<p>We can continue getting at deeply nested keys with the general approach of:</p>
<pre><code>m["first-key"]
.(map[string]interface{})["second-key"]
.(map[string]interface{})["third-key"]
{...}
</code></pre>
<p>Now imagine that we have a slice that represents the strings forming the deeply-nested key (e.g. <code>["oranges", "bar"]</code>), and a map we want to traverse.</p>
<p>Is there a way to write a function which does that? Here's a <a href="https://play.golang.org/p/1JXo5fvv7T">Go Playground link</a> that I've been working from.</p>
<hr/>**评论:**<br/><br/>1lann: <pre><p>Sure you can, using recursion: <a href="https://play.golang.org/p/0-CKUVYsE4">https://play.golang.org/p/0-CKUVYsE4</a></p>
<p>And one using iteration: <a href="https://play.golang.org/p/7ze54Hp9vi">https://play.golang.org/p/7ze54Hp9vi</a></p></pre>DavidDavidsonsGhost: <pre><p>I prefer your first one, but a type switch is a little cleaner I think: <a href="https://play.golang.org/p/zGAA5caVEk" rel="nofollow">https://play.golang.org/p/zGAA5caVEk</a></p></pre>Redundancy_: <pre><p>As a gentle counterpoint to being able to do it - can you not structure the data better so that it's well-typed and has a semantically consistent meaning? </p>
<p>I realize that this isn't always possible with other people's APIs etc.</p></pre>jxf: <pre><p>The map is the result of getting YAML back from a parser in use by a library that I don't control. Since, by definition, YAML represents arbitrarily structured data, it's hard to get more strongly typed than <code>map[string]interface{}</code> without becoming unwieldy.</p></pre>garaktailor: <pre><p>How about this: <a href="https://play.golang.org/p/WBE14HCqZw" rel="nofollow">https://play.golang.org/p/WBE14HCqZw</a></p>
<p>I use something like this when dealing with json that I don't necessarily have a nice schema for. </p></pre>MohamedBassem: <pre><p>Some people already answered but I was writing it anyways, so here you go : <a href="https://play.golang.org/p/cYldrwU3KA" rel="nofollow">https://play.golang.org/p/cYldrwU3KA</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传