Menu Close

Go – How to copy a map to another map in go

Here, We will see how to copy a map to another map in go . There are multiple ways to do that. We will see one by one by example and program.

In go, map is a collection of unordered pairs of key-value. To copy elements of one map to another, we can use for loop.

Example:

Suppose, you have a map of students records and you want copy these records to another map.

studs = {

    "john": 1,
    "rob": 2,
    "helaa": 3

}

Copy studs records to studs_tmp map. We will iterate each entry of studs map records and copy it to studs_tmp map.

Program 1:

package main

import (
        "fmt"
)

func main() {

    studs := map[string]int {

        "john": 1,
        "rob": 2,
        "helaa": 3,

    }

    studs_tmp := make(map[string]int)

    for name, roll_no := range studs {

        studs_tmp[name] = roll_no

    }

    for name, roll_no := range studs_tmp {

        fmt.Println("Name: ", name, ", roll_no: ", roll_no)

    }

}

Output:

 $ go run sample.go

 Name:  john , roll_no:  1

 Name:  rob , roll_no:  2

 Name:  helaa , roll_no:  3

Program 2

package main

import (
        "fmt"
)

func main() {

    studs := make(map[string]int)

    studs["john"] = 1
    studs["rob"] = 2
    studs["helaa"] = 3

    studs_tmp := make(map[string]int)

    for name, roll_no := range studs {

        studs_tmp[name] = roll_no

    }

    for name, roll_no := range studs_tmp {

        fmt.Println("Name: ", name, ", roll_no: ", roll_no)

    }

}

Output:

 $ go run sample.go

 Name:  john , roll_no:  1

 Name:  rob , roll_no:  2

 Name:  helaa , roll_no:  3

Program 3:

package main

import (
        "fmt"
)

func copy_map (m map[string]int) (map[string]int){

    studs_tmp := make(map[string]int)

    for name, roll_no := range m {

        studs_tmp[name] = roll_no

    }

    return studs_tmp

}

func main() {

    studs := map[string]int {

        "john": 1,
        "rob": 2,
        "helaa": 3,

    }


    copied_record := copy_map(studs)

    for name, roll_no := range copied_record {

        fmt.Println("Name: ", name, ", roll_no: ", roll_no)

    }

}

Output:

$ go run sample.go

 Name:  helaa , roll_no:  3

 Name:  john , roll_no:  1

 Name:  rob , roll_no:  2

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, Miscellaneous

Leave a Reply

Your email address will not be published.

Contact Us