Home  >  Article  >  Backend Development  >  How does the value in the Golang Map interface change?

How does the value in the Golang Map interface change?

WBOY
WBOYforward
2024-02-09 21:00:19917browse

Golang Map 接口中的值如何变化

How do the values ​​in the Golang Map interface change? This is a question that confuses many Golang developers. In Go language, map is a very important data structure, which stores data in the form of key-value pairs. However, when using map, we need to pay attention to some details, especially when dealing with value changes. So, let's take a closer look at how values ​​change in Golang's Map interface.

Question content

This is the code base - https://go.dev/play/p/bedouz9qhag

Output -

map[something:map[acm:34.12 age:12 dune:dune]]

What effect does changing the value of the t variable have on x?

package main

import "fmt"

    func main() {
        x: = make(map[string] interface {}, 10)
        x["something"] = map[string] interface {} {
            "dune": "dune", "age": 12
        }
    
        t: = x["something"].(map[string] interface {})
        t["ACM"] = 34.12
       

 fmt.Println(x)
}

Solution

The mapped type is a reference type, such as a pointer or slice,

So this line

t := x["something"].(map[string]interface{}) t["ACM"] = 34.12 fmt.Println(x) }

Just create a shallow copy of the existing map x you created in the alias variable, so they point to the same memory address where the original map you created is.

See reference -https://www.php.cn/link/0bf31d0d702fcac8c8e07912f3347c31

The above is the detailed content of How does the value in the Golang Map interface change?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete