{"id":10479,"date":"2024-06-04T12:25:59","date_gmt":"2024-06-04T12:25:59","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=10479"},"modified":"2024-06-04T12:26:31","modified_gmt":"2024-06-04T12:26:31","slug":"deep-copy-a-map-and-clear-the-original","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/golang\/deep-copy-a-map-and-clear-the-original","title":{"rendered":"How to Deep Copy a Map and Then Clear the Original"},"content":{"rendered":"<p>In Go (Golang), maps are reference types, which means that copying a map only creates a shallow copy. To create a deep copy of a map, especially when it contains nested structures, you need to manually copy each element. Once the deep copy is created, you can then clear the original map. This blog post will guide you through the process.<\/p>\n<p>Deep Copying a Map in Go<br \/>\nLet&#8217;s start by understanding the structure of a map in Go. A map is a collection of key-value pairs where each key is unique. Here\u2019s how you can perform a deep copy of a map and then clear the original:<\/p>\n<h3>Step-by-Step Process<\/h3>\n<p>Define the Map Structure: Depending on the type of values your map holds, you might need to create custom types or structs.<br \/>\nCreate a Deep Copy Function: This function will recursively copy each element of the map.<br \/>\nClear the Original Map: This is straightforward in Go using the delete function within a loop.<br \/>\n<strong>Example<\/strong><br \/>\nConsider a map with string keys and values of type interface{} to allow for nested structures. Here\u2019s how you can deep copy such a map and clear the original:<\/p>\n<p>Define the Original Map<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"golang\">package main\r\n\r\nimport (\r\n    \"fmt\"\r\n)\r\nfunc main() {\r\n    \/\/ Original map\r\n    originalMap := map[string]interface{}{\r\n        \"key1\": []int{1, 2, 3},\r\n        \"key2\": map[string]string{\"subkey1\": \"value1\"},\r\n    }\r\n\r\n    \/\/ Perform deep copy\r\n    deepCopiedMap := deepCopy(originalMap)\r\n\r\n    \/\/ Clear the original map\r\n    clearMap(originalMap)\r\n\r\n    fmt.Println(\"Deep Copied Map:\", deepCopiedMap)\r\n    fmt.Println(\"Original Map after clearing:\", originalMap)\r\n}\r\nDeep Copy Function\r\n\r\nfunc deepCopy(original map[string]interface{}) map[string]interface{} {\r\n    copy := make(map[string]interface{})\r\n    for key, value := range original {\r\n        switch v := value.(type) {\r\n        case map[string]interface{}:\r\n            copy[key] = deepCopy(v)\r\n        case []interface{}:\r\n            copy[key] = deepCopySlice(v)\r\n        case []int:\r\n            copy[key] = deepCopyIntSlice(v)\r\n        default:\r\n            copy[key] = value\r\n        }\r\n    }\r\n    return copy\r\n}\r\n\r\nfunc deepCopySlice(original []interface{}) []interface{} {\r\n    copy := make([]interface{}, len(original))\r\n    for i, value := range original {\r\n        switch v := value.(type) {\r\n        case map[string]interface{}:\r\n            copy[i] = deepCopy(v)\r\n        case []interface{}:\r\n            copy[i] = deepCopySlice(v)\r\n        default:\r\n            copy[i] = value\r\n        }\r\n    }\r\n    return copy\r\n}\r\n\r\nfunc deepCopyIntSlice(original []int) []int {\r\n    copy := make([]int, len(original))\r\n    copy(copy, original)\r\n    return copy\r\n}\r\nClear Function\r\n\r\nfunc clearMap(original map[string]interface{}) {\r\n    for key := range original {\r\n        delete(original, key)\r\n    }\r\n}\r\n<\/pre>\n<p>&nbsp;<br \/>\n<strong>Explanation<br \/>\nDeep Copy Function:<\/strong><\/p>\n<p>The deepCopy function creates a new map and iterates over the original map.<br \/>\nIt checks the type of each value and recursively copies maps and slices.<br \/>\nFor basic types, it assigns the value directly.<br \/>\nSlice Handling:<\/p>\n<p>The deepCopySlice function handles slices of interface{} by recursively copying each element.<br \/>\nThe deepCopyIntSlice function handles slices of integers directly using the copy function.<br \/>\nClearing the Map:<\/p>\n<p>The clearMap function iterates over the original map\u2019s keys and deletes each one.<br \/>\nBy following this approach, you ensure that you create a true deep copy of your map, preserving the integrity of your data, and then clear the original map efficiently. This is particularly useful when you need to reuse the original map without carrying over any previous data.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Go (Golang), maps are reference types, which means that copying a map only creates a shallow copy. To create a deep copy of a map, especially when it contains nested structures, you need to manually copy each element. Once the deep copy is created, you can then clear the original map. This blog post [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":10468,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[7],"tags":[],"class_list":["post-10479","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-golang"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/10479"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=10479"}],"version-history":[{"count":3,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/10479\/revisions"}],"predecessor-version":[{"id":10482,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/10479\/revisions\/10482"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/10468"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=10479"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=10479"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=10479"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}