1.

How can we copy a slice and a map in Go?

Answer»
  • To copy a slice: We can use the built-in method CALLED copy() as shown below:
slice1 := []int{1, 2}slice2 := []int{3, 4}slice3 := slice1copy(slice1, slice2)fmt.Println(slice1, slice2, slice3)

In the above example, we are copying the value of slice2 into slice1 and we are using the variable slice3 for holding a REFERENCE to the original slice to check if the slice has been copied or not. The output of the above code would be:

[3 4] [3 4] [3 4]

If we want to copy the slice description alone and not the contents, then we can do it by using the = operator as shown in the code below:

slice1 := []int{1, 2}slice2 := []int{3, 4}slice3 := slice1slice1 = slice2fmt.Println(slice1, slice2, slice3)

The output of the code will be:

[3 4] [3 4] [1 2]

Here, we can see that the contents of slice3 are not changed due to the = operator.

  • To copy a MAP in Go: We can copy a map by traversing the keys of the map. There is no built-in method to copy the map. The code for achieving this will be:
MAP1 := map[string]bool{"Interview": true, "Bit": true}map2 := make(map[string]bool)for key, value := RANGE map1 { map2[key] = value}

From this code, we are iterating the contents of map1 and then adding the values to map2 to the corresponding key.

If we want to copy just the description and not the content of the map, we can again use the = operator as shown below:

map1 := map[string]bool{"Interview": true, "Bit": true}map2 := map[string]bool{"Interview": true, "Questions": true}map3 := map1map1 = map2 //copy descriptionfmt.Println(map1, map2, map3)

The output of the below code would be:

map[Interview:true Questions:true] map[Interview:true Questions:true] map[Interview:true Bit:true]


Discussion

No Comment Found