Sobes.tech
Junior — Middle

How to insert or update a value for a specific key in a Map data structure in Go?

sobes.tech AI

Answer from AI

In Go, inserting or updating a value by key in a data structure map is done with simple assignment. If the key already exists, the value is updated; if not, a new key-value pair is created.

Example:

m := make(map[string]int)

// Insert a new value
m["key1"] = 100

// Update the value by key
m["key1"] = 200

// Check if the key exists
value, exists := m["key1"]
if exists {
    fmt.Println("Value for key1:", value)
} else {
    fmt.Println("Key key1 not found")
}

Thus, the insert and update operation in a map in Go boils down to assigning a value by key.