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

How does the value in the Golang Map interface change?

WBOY
Release: 2024-02-09 21:00:19
forward
951 people have browsed it

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]]
Copy after login

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)
}
Copy after login

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) }
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template