Cookies management by TermsFeed Cookie Consent

💕 Copy a map in Go

introduction map

Please consider supporting us by disabling your ad blocker

Maps in Go are reference types, so to deep copy the contents of a map, you cannot assign one instance to another. You can do this by creating a new, empty map and then iterating over the old map in a for range loop to assign the appropriate key-value pairs to the new map. It is the simplest and most efficient solution to this problem in Go.

package main

import "fmt"

func main() {
    fruitRank := map[string]int{
        "strawberry": 1,
        "blueberry":  2,
        "raspberry":  3,
    }

    // copy a map
    fruitRankCopy := make(map[string]int)
    for k, v := range fruitRank {
        fruitRankCopy[k] = v
    }
    fruitRankCopy["apple"] = 4

    fmt.Println("original map")
    fmt.Println(fruitRank)

    fmt.Println("copied map")
    fmt.Println(fruitRankCopy)
}

Output:

original map
map[blueberry:2 raspberry:3 strawberry:1]
copied map
map[apple:4 blueberry:2 raspberry:3 strawberry:1]

As you see in the output, the copied map is a deep clone, and adding new elements does not affect the old map.


Be careful when making a shallow copy by assigning one map to another. In this case, a modification in either map will cause a change in the data of both maps.

package main

import "fmt"

func main() {
    fruitRank := map[string]int{
        "strawberry": 1,
        "blueberry":  2,
        "raspberry":  3,
    }

    fruitRankShallowCopy := fruitRank
    fruitRankShallowCopy["apple"] = 4

    fmt.Println("original map")
    fmt.Println(fruitRank)

    fmt.Println("copied map")
    fmt.Println(fruitRankShallowCopy)
}

Output:

original map
map[apple:4 blueberry:2 raspberry:3 strawberry:1]
copied map
map[apple:4 blueberry:2 raspberry:3 strawberry:1]

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

🗝️ Check if a map contains a key in Go

Learn how to check if a key exists in a map
introduction map

❤️‍🩹 Recover function in Go

Learn what it is for and how to use the built-in recover() function
introduction syntax builtin

🐾 How to compare strings in Go

shorts introduction strings