Changing values in a slice inside a map...

agolangf · · 607 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I got it working using the below code, but my &#39;solution&#39; as it were seems very clunky. Essentially copy all contents of a map key to a temp struct, use the temp struct to append a new value, delete the map entry at given key, re-create the map entry at a given key with new value from the temp struct.</p> <p>There must be a better way?!</p> <pre><code>package main import ( &#34;crypto/sha1&#34; &#34;fmt&#34; &#34;hash&#34; &#34;io&#34; &#34;math/rand&#34; &#34;time&#34; ) type myStructT struct { name string pets []string } func main() { myMap := make(map[string]myStructT) rand.Seed(time.Now().UTC().UnixNano()) mySlice := initSlice() myMap = initMap(mySlice) printMap(myMap) myMap = editMap(myMap, &#34;Dewey&#34;) fmt.Println(&#34;----- After edit -----&#34;) printMap(myMap) } func editMap(in map[string]myStructT, index string) map[string]myStructT { var h hash.Hash var hash string var old myStructT h = sha1.New() io.WriteString(h, index) hash = fmt.Sprintf(&#34;%x&#34;, h.Sum(nil)) old = in[hash] delete(in, hash) old.pets = append(old.pets, &#34;Alligator&#34;) in[hash] = old return in } func printMap(in map[string]myStructT) { for i := range in { fmt.Printf(&#34;Name: %s\n&#34;, in[i].name) if len(in[i].pets) &gt; 0 { fmt.Printf(&#34;Pets: %d\n&#34;, len(in[i].pets)) for j := range in[i].pets { fmt.Printf(&#34;- %s\n&#34;, in[i].pets[j]) } } else { fmt.Println(&#34;No Pets :(&#34;) } fmt.Println(&#34;----------&#34;) } } func initSlice() []myStructT { var s myStructT var out []myStructT name := [3]string{&#34;Huey&#34;, &#34;Luie&#34;, &#34;Dewey&#34;} pets := [6]string{&#34;Cat&#34;, &#34;Dog&#34;, &#34;Ferret&#34;, &#34;Bunny&#34;, &#34;Hamster&#34;, &#34;Parrot&#34;} for i := range name { s.name = name[i] s.pets = nil x := randInt(0, 3) for j := 0; j &lt; x; j++ { y := randInt(0, 6) s.pets = append(s.pets, pets[y]) } out = append(out, s) } return out } func initMap(in []myStructT) map[string]myStructT { var h hash.Hash var hash string var s myStructT out := make(map[string]myStructT) for i := range in { h = sha1.New() io.WriteString(h, in[i].name) hash = fmt.Sprintf(&#34;%x&#34;, h.Sum(nil)) s = in[i] out[hash] = s } return out } func randInt(min int, max int) int { return min + rand.Intn(max-min) } </code></pre> <p>edit: Post title should be &#34;Changing values in a slice in a struct in a map&#34; come to think of it...</p> <p>ʕ◔ϖ◔ʔ</p> <hr/>**评论:**<br/><br/>RenThraysk: <pre><p>Using pointers will remove the clunk, map[string]*myStructT</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

607 次点击  
加入收藏 微博
1 回复  |  直到
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传