简体   繁体   中英

golang updating slice value is not reflected in container object

package main

import (
    "fmt"

)

func main() {
    root := map[string]interface{} {
        "disney": "world",  
    }
    fmt.Printf("main begin %v\n", root)
    addList(root)
    fmt.Printf("main after addList %v\n", root)
    addMap(root)
    fmt.Printf("main after addMap  %v\n", root)
}

func addList(root map[string]interface{}) {
    root["list"] = make([]interface{},0,3) 
    mylist := root["list"]
    mylist = append(mylist.([]interface{}),"mickeymouse")
    fmt.Printf("addList %v\n", mylist)
    fmt.Printf("addList %v\n", root)
}

func addMap(root map[string]interface{}) {
    root["map"] = make(map[string]interface{})
    mymap := root["map"]
    mymap.(map[string]interface{})["donald"] = "duck"
    fmt.Printf("addMap %v\n", mymap)
    fmt.Printf("addMap %v\n", root)
}

I have a root map having the pair "disney"->"world". To that root map I added a slice having "mickeymouse" in function addList, followed by adding a map with pair "donald"->"duck" in function addMap. However the slice does not get added, whereas the map gets added to the root map. The child map is expected behavior, but the slice addition seems to be an anomaly. I thought the slice was a reference just like a map in golang. What is going on in this case? It would have worked in Java. Where am I going wrong? How can I make it work? In the actual larger problem I dont have the option of returning anything except an error from the functions.

  • The append function returns a new slice.
  • Storing values in a map will not produce a new map.

It is therefore only natural that you do not see the new slice, but you do see the map's content updated.

How can I make it work?

Store the new slice in place of the old, eg

mylist := root["list"]
mylist = append(mylist.([]interface{}),"mickeymouse")
root["list"] = mylist

// or, doing it on one line
root["list"] = append(root["list"].([]any), "mickeymouse")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM