Câu hỏi phỏng vấn Golang
Câu hỏi

How to copy Map in Go?

Câu trả lời

Copying a map in Go (Golang) involves creating a new map and then transferring the key-value pairs from the original map to the new one. This can be done in several ways, depending on whether you need a shallow copy or a deep copy of the map. Here are the methods to copy a map in Go:

Shallow Copy

A shallow copy of a map can be achieved by simply iterating over the original map and copying each key-value pair to a new map. This method is suitable when the values in the map are basic data types or if you do not need to duplicate the values that are reference types (like slices, maps, or pointers).

go Copy
func main() {
    originalMap := map[string]int{"Alice": 25, "Bob": 22, "John": 20}
    newMap := make(map[string]int)
    for key, value := range originalMap {
        newMap[key] = value
    }
    fmt.Println("Original Map:", originalMap)
    fmt.Println("Copied Map:", newMap)
}

Deep Copy

A deep copy is necessary when the map contains reference types and you want the copied map to be entirely independent of the original map. Go does not have a built-in function for deep copying maps, but you can achieve this by using various techniques such as JSON marshaling and unmarshaling, creating custom functions, or using third-party libraries[1].

Here is an example using JSON for deep copying a map:

go Copy
import (
    "encoding/json"
    "log"
)

func deepCopyMap(originalMap map[string]interface{}) (map[string]interface{}, error) {
    var newMap map[string]interface{}
    bytes, err := json.Marshal(originalMap)
    if err != nil {
        return nil, err
    }
    err = json.Unmarshal(bytes, &newMap)
    if err != nil {
        return nil, err
   ...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between C.sleep() and time.Sleep() ?

middle

Have you worked with Go 2?

senior

What is the difference, if any, in the following two slice declarations, and which one is more preferable?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào