<p>I got it working using the below code, but my 'solution' 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 (
"crypto/sha1"
"fmt"
"hash"
"io"
"math/rand"
"time"
)
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, "Dewey")
fmt.Println("----- After edit -----")
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("%x", h.Sum(nil))
old = in[hash]
delete(in, hash)
old.pets = append(old.pets, "Alligator")
in[hash] = old
return in
}
func printMap(in map[string]myStructT) {
for i := range in {
fmt.Printf("Name: %s\n", in[i].name)
if len(in[i].pets) > 0 {
fmt.Printf("Pets: %d\n", len(in[i].pets))
for j := range in[i].pets {
fmt.Printf("- %s\n", in[i].pets[j])
}
} else {
fmt.Println("No Pets :(")
}
fmt.Println("----------")
}
}
func initSlice() []myStructT {
var s myStructT
var out []myStructT
name := [3]string{"Huey", "Luie", "Dewey"}
pets := [6]string{"Cat", "Dog", "Ferret", "Bunny", "Hamster", "Parrot"}
for i := range name {
s.name = name[i]
s.pets = nil
x := randInt(0, 3)
for j := 0; j < 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("%x", 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 "Changing values in a slice in a struct in a map" 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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传